Browse Source

订单期数修改,连同流水表期数

theo 2 years ago
parent
commit
21f9fd105d

+ 1 - 0
backendApi/config/menu.php

@@ -58,6 +58,7 @@ return [
             ['name'=>'External mall order list', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-shop-list', 'routePath'=>'shop/order-shop-list', 'show'=>1, 'wiki' => 'externalMallOrderList'], // 外部商城订单列表
             ['name'=>'External mall entry list', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-dec-list', 'routePath'=>'shop/order-dec-list', 'show'=>1, 'wiki' => 'externalMallEntryList'], // 外部商城报单列表
             // ['name'=>'List of qualified orders of external mall', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-standard-list', 'routePath'=>'shop/order-standard-list', 'show'=>1,], // 外部商城达标订单列表
+            ['name'=>'订单期数调整', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-period-adjust', 'routePath'=>'shop/order-period-adjust', 'show'=>1, 'wiki' => 'shopOrderPeriodAdjust'],
 //            ['name'=>'Brand Ambassador Order', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'ba-order-list', 'routePath'=>'shop/ba-order-list', 'show'=>1,], // 会员列表
 //            ['name'=>'Brand Ambassador Dec List', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'ba-dec-order-list', 'routePath'=>'shop/ba-dec-order-list', 'show'=>1,], // 会员列表
 

+ 3 - 0
backendApi/config/urlManagerRules.php

@@ -72,6 +72,9 @@ return [
             'GET ba-order-list' => 'ba-order-list',
             'GET ba-order-list-export' => 'ba-order-list-export',
             'GET ba-order-list-export-pdf/<orderSn>' => 'ba-order-list-export-pdf',
+            'GET,POST order-period-adjust' => 'order-period-adjust',
+            'GET order-detail' => 'order-detail',
+            'GET period-inspect' => 'period-inspect',
         ],
     ],
     [

+ 70 - 2
backendApi/modules/v1/controllers/ShopController.php

@@ -15,6 +15,7 @@ use backendApi\modules\v1\models\lists\shop\GoodsList;
 use backendApi\modules\v1\models\lists\shop\OrderDecList;
 use backendApi\modules\v1\models\lists\shop\OrderList;
 use backendApi\modules\v1\models\lists\shop\BaOrderList;
+use backendApi\modules\v1\models\lists\shop\OrderPeriodAdjustList;
 use backendApi\modules\v1\models\lists\shop\OrderShopList;
 use backendApi\modules\v1\models\lists\shop\OrderStandardList;
 use backendApi\modules\v1\models\lists\shop\PackageList;
@@ -31,8 +32,11 @@ use common\models\forms\ExcelOrderShopForm;
 use common\models\forms\ExcelOrderStandardForm;
 use common\models\forms\OrderDeleteForm;
 use common\models\forms\OrderForm;
+use common\models\forms\OrderPeriodAdjustForm;
 use common\models\forms\ShopGoodsForm;
 use common\models\forms\UploadForm;
+use common\models\Order;
+use common\models\Period;
 use common\models\ShopGoods;
 use yii\web\HttpException;
 use yii\web\UploadedFile;
@@ -364,7 +368,7 @@ class ShopController extends BaseController {
         if (\Yii::$app->request->isPost) {
             $formModel = new OrderDeleteForm();
             if ($formModel->load(\Yii::$app->request->post(), '') && $result = $formModel->returnOrder()) {
-                
+
                 return static::notice(\Yii::t('ctx', 'shopDelOrderSuccedNotice'));
             } else {
                 return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
@@ -846,4 +850,68 @@ class ShopController extends BaseController {
         }
         return static::notice(\Yii::t('ctx', 'startExporting')); // 导出开始,请到文件管理-导出文件查看
     }
-}
+
+    /**
+     * 调整订单期数
+     * @return mixed
+     * @throws Exception
+     * @throws \yii\db\Exception
+     * @throws \yii\web\HttpException
+     */
+    public function actionOrderPeriodAdjust()
+    {
+        if (\Yii::$app->request->isPost) {
+            $formModel = new OrderPeriodAdjustForm();
+            $formModel->scenario = 'orderPeriodAdjust';
+            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->periodAdjust()) {
+                return static::notice('成功');
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
+            }
+        } else {
+            $filter = $this->filterCondition([
+                'ORDER_SN' => 'P.ORDER_SN',
+                'ORIGIN_PERIOD'=> 'P.ORIGIN_PERIOD',
+                'MODERN_PERIOD'=> 'P.MODERN_PERIOD',
+                'CREATED_AT'=> 'P.CREATED_AT',
+            ]);
+            $listObj = new OrderPeriodAdjustList();
+            $data = $listObj->getList(['condition' => $filter['condition'], 'params' => $filter['params']]);
+            return static::notice($data);
+        }
+    }
+
+    /**
+     * 订单详情
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionOrderDetail()
+    {
+        $orderSn = \Yii::$app->request->get('orderSn');
+
+        $order = Order::findOneAsArray('SN=:SN', [':SN' => $orderSn]);
+        if (!$order) {
+            return static::notice('订单不存在', 400);
+        }
+        $order['ORDER_TYPE'] = $order['ORDER_TYPE'] === 'ZC' ? '首单' : '复消';
+        // 如果当前订单所在期数已挂网,则不可调整
+        $period = Period::getInfoByPeriodNum($order['PERIOD_NUM']);
+        if (!$period) {
+            return static::notice('期数无效', 400);
+        }
+        if ($period['IS_SENT'] > 0) {
+            return static::notice('订单已挂网', 400);
+        }
+        // 根据订单期数查询可调整期数
+        $availablePeriod = [];
+        if ($order['PERIOD_NUM']) {
+            $availablePeriod = Period::getPeriodList(+$order['PERIOD_NUM'] - 1);
+            foreach ($availablePeriod as $k => $item) {
+                $availablePeriod[$k]['disabled'] = (+$item['IS_SENT'] > 0) || ($order['PERIOD_NUM'] == $item['PERIOD_NUM']);
+            }
+        }
+
+        return static::notice(['order' => $order, 'availablePeriod' => $availablePeriod]);
+    }
+}

+ 230 - 226
backendApi/modules/v1/models/lists/bonus/FlowBalanceList.php

@@ -1,226 +1,230 @@
-<?php
-
-namespace backendApi\modules\v1\models\lists\bonus;
-
-use common\helpers\Cache;
-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\DealType;
-use common\models\FlowWallet;
-use common\libs\dataList\column\DateTime;
-use Yii;
-
-class FlowBalanceList extends \common\libs\dataList\DataList implements DataListInterface {
-    /**
-     * 列表名称
-     * @return string
-     */
-    public function getListName() {
-        return '会员余额流水';
-    }
-
-    /**
-     * 列表筛选到的数据
-     * @throws \yii\base\Exception
-     */
-    public function dataHandle() {
-        
-        $this->listData = FlowWallet::lists($this->condition, $this->params, [
-            'select' => 'FW.TRANSFER_SN,FW.USER_ID,FW.AMOUNT,FW.TOTAL,FW.IS_INCR,FW.REMARK,FW.PERIOD_NUM,FW.CALC_MONTH,FW.CREATED_AT,
-            U.USER_NAME,U.REAL_NAME,U.IS_DEC',
-            'orderBy' => 'FW.CREATED_AT DESC,FW.SORT DESC',
-            'from' => FlowWallet::tableName() . ' AS FW',
-            'join' => [
-                ['INNER JOIN', \common\models\User::tableName() . ' AS U', 'FW.USER_ID=U.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'] ?? '';
-        //     // $this->listData['list'][$key]['LAST_STATUS_NAME'] = \Yii::$app->params['userStatus'][$value['LAST_STATUS']]['label'] ?? '';
-        // }
-
-    }
-
-    /**
-     * 要展示和导出的所有字段
-     * @return array
-     */
-    public function getColumn() {
-        if (!$this->columns) {
-            $this->columns = [
-                // 'ID' => null,
-                'CREATED_AT' => [
-                    'header' => '创建时间',
-                    'value' => function ($row) {
-                        return (new DateTime([
-                            'value' => $row['CREATED_AT'],
-                        ]))->result();
-                    },
-                    'headerOther' => ['width' => '170'],
-                ],
-                'PERIOD_NUM' => '期数',
-                'CALC_MONTH' => '结算月',
-                'USER_NAME' => [
-                    'header' => '会员编号',
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'info', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                'REAL_NAME' => [
-                    'header' => '会员姓名',
-                    'headerOther' => [
-                        'width' => '120',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'success', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                // 'LAST_DEC_LV_NAME' => [
-                //     'header' => '会员级别',
-                //     'headerOther' => [
-                //         'width' => '110',
-                //     ],
-                //     'valueOther' => [
-                //         'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
-                //     ],
-                // ],
-                // 'LAST_EMP_LV_NAME' => [
-                //     'header' => '聘级',
-                //     'headerOther' => [
-                //         'width' => '130',
-                //     ],
-                //     'valueOther' => [
-                //         'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
-                //     ],
-                // ],
-//                'LAST_STATUS_NAME' => [
-//                    'header' => '会员状态',
-//                    'headerOther' => ['width' => '110'],
-//                ],
-//                'SYSTEM_NAME' => [
-//                    'header' => '体系',
-//                    'headerOther' => ['width' => '200'],
-//                ],
-                'IS_DEC' => [
-                    'header' => '是否报单中心',
-                    'value' => function ($row) {
-                        return (new YesNo([
-                            'value' => $row['IS_DEC'],
-                        ]))->result();
-                    },
-                    'headerOther' => function ($row) {
-                        return [
-                            'width' => '120',
-                        ];
-                    },
-                    'valueOther' => function ($row) {
-                        return [
-                            'tag' => ['type' => (isset($row['IS_DEC']) && $row['IS_DEC']) ? 'success' : 'info', 'size' => 'small']
-                        ];
-                    },
-                ],
-                'BEFORE_BALANCE' => [
-                    'header' => '交易前余额',
-                    'value' => function ($row) {
-                        return (new Price([
-                            'value' => $row['TOTAL'] - $row['AMOUNT'],
-                        ]))->result();
-                    },
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                ],
-                'AMOUNT' => [
-                    'header' => '交易额',
-                    'value' => function ($row) {
-                        $result = (new Price([
-                            'value' => $row['AMOUNT'],
-                        ]))->result();
-                        return $row['IS_INCR'] > 0 ? '+' . $result : $result;
-                    },
-                    'headerOther' => [
-                        'width' => '150',
-                        'prop' => 'BONUS',
-                    ],
-                    'valueOther' => function ($row) {
-                        if ($row['IS_INCR'] > 0) {
-                            $type = 'success';
-                        } elseif ($row['IS_INCR'] == 0) {
-                            $type = 'danger';
-                        } else {
-                            $type = 'info';
-                        }
-                        return [
-                            'tag' => ['type' => $type, 'size' => 'small']
-                        ];
-                    },
-                ],
-                'TOTAL' => [
-                    'header' => '交易后余额',
-                    'value' => function ($row) {
-                        return (new Price([
-                            'value' => $row['TOTAL'],
-                        ]))->result();
-                    },
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                ],
-                // 'ADMIN_NAME' => [
-                //     'header' => '操作人',
-                //     'headerOther' => ['width' => '110'],
-                // ],
-                'REMARK' => [
-                    'header' => '备注',
-                    'headerOther' => ['width' => '250'],
-                ],
-                'TRANSFER_SN' => [
-                    'header' => '流水号',
-                    'headerOther' => ['width' => '250'],
-                ],
-            ];
-        }
-        return $this->columns;
-    }
-
-    /**
-     * 前台用于筛选的类型集合
-     * @return mixed
-     */
-    public function getFilterTypes() {
-        if (!$this->filterTypes) {
-            $this->filterTypes = [
-                'CREATED_AT' => ['isUserTable' => false, 'name' => '创建时间', 'other' => 'date'],
-                'PERIOD_NUM' => ['isUserTable' => false, 'name' => '期数'],
-                'CALC_MONTH' => ['isUserTable' => false, 'name' => '结算月', 'other' => 'month'],
-                'DEAL_TYPE_NAME' => ['isUserTable' => false, 'name' => '交易类型', 'other' => 'dealTypes'],
-                'USER_NAME' => ['isUserTable' => false, 'name' => '会员编号'],
-                'REAL_NAME' => ['isUserTable' => false, 'name' => '会员姓名'],
-//                 'LAST_DEC_LV_NAME' => ['isUserTable' => false, 'name' => '会员级别', 'other' => 'decLevel'],
-//                 'LAST_EMP_LV_NAME' => ['isUserTable' => false, 'name' => '聘级', 'other' => 'empLevel'],
-// //                'LAST_STATUS_NAME' => ['isUserTable' => false, 'name' => '会员状态', 'other' => 'status'],
-// //                'SYSTEM_NAME' => ['isUserTable' => true, 'name' => '体系', 'other' => 'systems'],
-//                 'IS_DEC' => ['isUserTable' => false, 'name' => '是否报单中心', 'other' => 'yesOrNo'],
-//                'DEC_ROLE_NAME' => ['isUserTable' => true, 'name' => '报单中心级别', 'other' => 'decRole'],
-//                'IS_DIRECT_SELLER' => ['isUserTable' => true, 'name' => '是否直销员', 'other' => 'yesOrNo'],
-                'AMOUNT' => ['isUserTable' => false, 'name' => '交易额'],
-                'TOTAL' => ['isUserTable' => false, 'name' => '交易后余额'],
-                'ADMIN_NAME' => ['isUserTable' => false, 'name' => '操作人'],
-                'REMARK' => ['isUserTable' => false, 'name' => '备注'],
-                'TRANSFER_SN' => ['isUserTable' => false, 'name' => '流水号'],
-            ];
-        }
-        return $this->filterTypes;
-    }
-}
+<?php
+
+namespace backendApi\modules\v1\models\lists\bonus;
+
+use common\helpers\Cache;
+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\DealType;
+use common\models\FlowWallet;
+use common\libs\dataList\column\DateTime;
+use Yii;
+
+class FlowBalanceList extends \common\libs\dataList\DataList implements DataListInterface {
+    /**
+     * 列表名称
+     * @return string
+     */
+    public function getListName() {
+        return '会员余额流水';
+    }
+
+    /**
+     * 列表筛选到的数据
+     * @throws \yii\base\Exception
+     */
+    public function dataHandle() {
+
+        $this->listData = FlowWallet::lists($this->condition, $this->params, [
+            'select' => 'FW.ORDER_SN,FW.TRANSFER_SN,FW.USER_ID,FW.AMOUNT,FW.TOTAL,FW.IS_INCR,FW.REMARK,FW.PERIOD_NUM,FW.CALC_MONTH,FW.CREATED_AT,
+            U.USER_NAME,U.REAL_NAME,U.IS_DEC',
+            'orderBy' => 'FW.CREATED_AT DESC,FW.SORT DESC',
+            'from' => FlowWallet::tableName() . ' AS FW',
+            'join' => [
+                ['INNER JOIN', \common\models\User::tableName() . ' AS U', 'FW.USER_ID=U.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'] ?? '';
+        //     // $this->listData['list'][$key]['LAST_STATUS_NAME'] = \Yii::$app->params['userStatus'][$value['LAST_STATUS']]['label'] ?? '';
+        // }
+
+    }
+
+    /**
+     * 要展示和导出的所有字段
+     * @return array
+     */
+    public function getColumn() {
+        if (!$this->columns) {
+            $this->columns = [
+                // 'ID' => null,
+                'CREATED_AT' => [
+                    'header' => '创建时间',
+                    'value' => function ($row) {
+                        return (new DateTime([
+                            'value' => $row['CREATED_AT'],
+                        ]))->result();
+                    },
+                    'headerOther' => ['width' => '170'],
+                ],
+                'PERIOD_NUM' => '期数',
+                'CALC_MONTH' => '结算月',
+                'USER_NAME' => [
+                    'header' => '会员编号',
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'info', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                'REAL_NAME' => [
+                    'header' => '会员姓名',
+                    'headerOther' => [
+                        'width' => '120',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'success', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                // 'LAST_DEC_LV_NAME' => [
+                //     'header' => '会员级别',
+                //     'headerOther' => [
+                //         'width' => '110',
+                //     ],
+                //     'valueOther' => [
+                //         'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
+                //     ],
+                // ],
+                // 'LAST_EMP_LV_NAME' => [
+                //     'header' => '聘级',
+                //     'headerOther' => [
+                //         'width' => '130',
+                //     ],
+                //     'valueOther' => [
+                //         'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
+                //     ],
+                // ],
+//                'LAST_STATUS_NAME' => [
+//                    'header' => '会员状态',
+//                    'headerOther' => ['width' => '110'],
+//                ],
+//                'SYSTEM_NAME' => [
+//                    'header' => '体系',
+//                    'headerOther' => ['width' => '200'],
+//                ],
+                'IS_DEC' => [
+                    'header' => '是否报单中心',
+                    'value' => function ($row) {
+                        return (new YesNo([
+                            'value' => $row['IS_DEC'],
+                        ]))->result();
+                    },
+                    'headerOther' => function ($row) {
+                        return [
+                            'width' => '120',
+                        ];
+                    },
+                    'valueOther' => function ($row) {
+                        return [
+                            'tag' => ['type' => (isset($row['IS_DEC']) && $row['IS_DEC']) ? 'success' : 'info', 'size' => 'small']
+                        ];
+                    },
+                ],
+                'BEFORE_BALANCE' => [
+                    'header' => '交易前余额',
+                    'value' => function ($row) {
+                        return (new Price([
+                            'value' => $row['TOTAL'] - $row['AMOUNT'],
+                        ]))->result();
+                    },
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                'AMOUNT' => [
+                    'header' => '交易额',
+                    'value' => function ($row) {
+                        $result = (new Price([
+                            'value' => $row['AMOUNT'],
+                        ]))->result();
+                        return $row['IS_INCR'] > 0 ? '+' . $result : $result;
+                    },
+                    'headerOther' => [
+                        'width' => '150',
+                        'prop' => 'BONUS',
+                    ],
+                    'valueOther' => function ($row) {
+                        if ($row['IS_INCR'] > 0) {
+                            $type = 'success';
+                        } elseif ($row['IS_INCR'] == 0) {
+                            $type = 'danger';
+                        } else {
+                            $type = 'info';
+                        }
+                        return [
+                            'tag' => ['type' => $type, 'size' => 'small']
+                        ];
+                    },
+                ],
+                'TOTAL' => [
+                    'header' => '交易后余额',
+                    'value' => function ($row) {
+                        return (new Price([
+                            'value' => $row['TOTAL'],
+                        ]))->result();
+                    },
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                // 'ADMIN_NAME' => [
+                //     'header' => '操作人',
+                //     'headerOther' => ['width' => '110'],
+                // ],
+                'REMARK' => [
+                    'header' => '备注',
+                    'headerOther' => ['width' => '250'],
+                ],
+                'TRANSFER_SN' => [
+                    'header' => '流水号',
+                    'headerOther' => ['width' => '250'],
+                ],
+                'ORDER_SN' => [
+                    'header' => '订单号',
+                    'headerOther' => ['width' => '250'],
+                ],
+            ];
+        }
+        return $this->columns;
+    }
+
+    /**
+     * 前台用于筛选的类型集合
+     * @return mixed
+     */
+    public function getFilterTypes() {
+        if (!$this->filterTypes) {
+            $this->filterTypes = [
+                'CREATED_AT' => ['isUserTable' => false, 'name' => '创建时间', 'other' => 'date'],
+                'PERIOD_NUM' => ['isUserTable' => false, 'name' => '期数'],
+                'CALC_MONTH' => ['isUserTable' => false, 'name' => '结算月', 'other' => 'month'],
+                'DEAL_TYPE_NAME' => ['isUserTable' => false, 'name' => '交易类型', 'other' => 'dealTypes'],
+                'USER_NAME' => ['isUserTable' => false, 'name' => '会员编号'],
+                'REAL_NAME' => ['isUserTable' => false, 'name' => '会员姓名'],
+//                 'LAST_DEC_LV_NAME' => ['isUserTable' => false, 'name' => '会员级别', 'other' => 'decLevel'],
+//                 'LAST_EMP_LV_NAME' => ['isUserTable' => false, 'name' => '聘级', 'other' => 'empLevel'],
+// //                'LAST_STATUS_NAME' => ['isUserTable' => false, 'name' => '会员状态', 'other' => 'status'],
+// //                'SYSTEM_NAME' => ['isUserTable' => true, 'name' => '体系', 'other' => 'systems'],
+//                 'IS_DEC' => ['isUserTable' => false, 'name' => '是否报单中心', 'other' => 'yesOrNo'],
+//                'DEC_ROLE_NAME' => ['isUserTable' => true, 'name' => '报单中心级别', 'other' => 'decRole'],
+//                'IS_DIRECT_SELLER' => ['isUserTable' => true, 'name' => '是否直销员', 'other' => 'yesOrNo'],
+                'AMOUNT' => ['isUserTable' => false, 'name' => '交易额'],
+                'TOTAL' => ['isUserTable' => false, 'name' => '交易后余额'],
+                'ADMIN_NAME' => ['isUserTable' => false, 'name' => '操作人'],
+                'REMARK' => ['isUserTable' => false, 'name' => '备注'],
+                'TRANSFER_SN' => ['isUserTable' => false, 'name' => '流水号'],
+            ];
+        }
+        return $this->filterTypes;
+    }
+}

+ 211 - 207
backendApi/modules/v1/models/lists/bonus/FlowExchangePointsList.php

@@ -1,207 +1,211 @@
-<?php
-
-namespace backendApi\modules\v1\models\lists\bonus;
-
-use common\helpers\Cache;
-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\DealType;
-use common\libs\dataList\column\DateTime;
-use common\models\FlowExchangePoints;
-use Yii;
-
-class FlowExchangePointsList extends \common\libs\dataList\DataList implements DataListInterface {
-    /**
-     * 列表名称
-     * @return string
-     */
-    public function getListName() {
-        return '兑换积分流水';
-    }
-
-    /**
-     * 列表筛选到的数据
-     * @throws \yii\base\Exception
-     */
-    public function dataHandle() {
-        $this->listData = FlowExchangePoints::lists($this->condition, $this->params, [
-            'orderBy' => 'CREATED_AT DESC, ID DESC',
-            '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'] ?? '';
-            $this->listData['list'][$key]['LAST_STATUS_NAME'] = \Yii::$app->params['userStatus'][$value['LAST_STATUS']]['label'] ?? '';
-        }
-    }
-
-    /**
-     * 要展示和导出的所有字段
-     * @return array
-     */
-    public function getColumn() {
-        if (!$this->columns) {
-            $this->columns = [
-                'ID' => null,
-                'CREATED_AT' => [
-                    'header' => '创建时间',
-                    'value' => function ($row) {
-                        return (new DateTime([
-                            'value' => $row['CREATED_AT'],
-                        ]))->result();
-                    },
-                    'headerOther' => ['width' => '170'],
-                ],
-                'PERIOD_NUM' => '期数',
-                'CALC_MONTH' => '结算月',
-                'DEAL_TYPE_NAME' => [
-                    'header' => '交易类型',
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                ],
-                'USER_NAME' => [
-                    'header' => '会员编号',
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'info', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                'REAL_NAME' => [
-                    'header' => '会员姓名',
-                    'headerOther' => [
-                        'width' => '120',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'success', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                'LAST_DEC_LV_NAME' => [
-                    'header' => '会员级别',
-                    'headerOther' => [
-                        'width' => '110',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                'LAST_EMP_LV_NAME' => [
-                    'header' => '聘级',
-                    'headerOther' => [
-                        'width' => '130',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                'IS_DEC' => [
-                    'header' => '是否报单中心',
-                    'value' => function ($row) {
-                        return (new YesNo([
-                            'value' => $row['IS_DEC'],
-                        ]))->result();
-                    },
-                    'headerOther' => function ($row) {
-                        return [
-                            'width' => '120',
-                        ];
-                    },
-                    'valueOther' => function ($row) {
-                        return [
-                            'tag' => ['type' => (isset($row['IS_DEC']) && $row['IS_DEC']) ? 'success' : 'info', 'size' => 'small']
-                        ];
-                    },
-                ],
-                'BEFORE_BALANCE' => [
-                    'header' => '交易前余额',
-                    'value' => function ($row) {
-                        return (new Price([
-                            'value' => $row['TOTAL'] - $row['AMOUNT'],
-                        ]))->result();
-                    },
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                ],
-                'AMOUNT' => [
-                    'header' => '交易额',
-                    'value' => function ($row) {
-                        $result = (new Price([
-                            'value' => $row['AMOUNT'],
-                        ]))->result();
-                        return $row['IS_INCR'] > 0 ? '+' . $result : $result;
-                    },
-                    'headerOther' => [
-                        'width' => '150',
-                        'prop' => 'BONUS',
-                    ],
-                    'valueOther' => function ($row) {
-                        if ($row['IS_INCR'] > 0) {
-                            $type = 'success';
-                        } elseif ($row['IS_INCR'] == 0) {
-                            $type = 'danger';
-                        } else {
-                            $type = 'info';
-                        }
-                        return [
-                            'tag' => ['type' => $type, 'size' => 'small']
-                        ];
-                    },
-                ],
-                'TOTAL' => [
-                    'header' => '交易后余额',
-                    'value' => function ($row) {
-                        return (new Price([
-                            'value' => $row['TOTAL'],
-                        ]))->result();
-                    },
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                ],
-                'ADMIN_NAME' => [
-                    'header' => '操作人',
-                    'headerOther' => ['width' => '110'],
-                ],
-                'REMARK' => [
-                    'header' => '备注',
-                    'headerOther' => ['width' => '250'],
-                ],
-            ];
-        }
-        return $this->columns;
-    }
-
-    /**
-     * 前台用于筛选的类型集合
-     * @return mixed
-     */
-    public function getFilterTypes() {
-        if (!$this->filterTypes) {
-            $this->filterTypes = [
-                'CREATED_AT' => ['isUserTable' => false, 'name' => '创建时间', 'other' => 'date'],
-                'PERIOD_NUM' => ['isUserTable' => false, 'name' => '期数'],
-                'CALC_MONTH' => ['isUserTable' => false, 'name' => '结算月', 'other' => 'month'],
-                'DEAL_TYPE_NAME' => ['isUserTable' => false, 'name' => '交易类型', 'other' => 'dealTypes'],
-                'USER_NAME' => ['isUserTable' => true, 'name' => '会员编号'],
-                'REAL_NAME' => ['isUserTable' => true, 'name' => '会员姓名'],
-                'LAST_DEC_LV_NAME' => ['isUserTable' => false, 'name' => '会员级别', 'other' => 'decLevel'],
-                'LAST_EMP_LV_NAME' => ['isUserTable' => false, 'name' => '聘级', 'other' => 'empLevel'],
-                'IS_DEC' => ['isUserTable' => true, 'name' => '是否报单中心', 'other' => 'yesOrNo'],
-                'AMOUNT' => ['isUserTable' => false, 'name' => '交易额'],
-                'TOTAL' => ['isUserTable' => false, 'name' => '交易后余额'],
-                'ADMIN_NAME' => ['isUserTable' => false, 'name' => '操作人'],
-                'REMARK' => ['isUserTable' => false, 'name' => '备注'],
-            ];
-        }
-        return $this->filterTypes;
-    }
-}
+<?php
+
+namespace backendApi\modules\v1\models\lists\bonus;
+
+use common\helpers\Cache;
+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\DealType;
+use common\libs\dataList\column\DateTime;
+use common\models\FlowExchangePoints;
+use Yii;
+
+class FlowExchangePointsList extends \common\libs\dataList\DataList implements DataListInterface {
+    /**
+     * 列表名称
+     * @return string
+     */
+    public function getListName() {
+        return '兑换积分流水';
+    }
+
+    /**
+     * 列表筛选到的数据
+     * @throws \yii\base\Exception
+     */
+    public function dataHandle() {
+        $this->listData = FlowExchangePoints::lists($this->condition, $this->params, [
+            'orderBy' => 'CREATED_AT DESC, ID DESC',
+            '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'] ?? '';
+            $this->listData['list'][$key]['LAST_STATUS_NAME'] = \Yii::$app->params['userStatus'][$value['LAST_STATUS']]['label'] ?? '';
+        }
+    }
+
+    /**
+     * 要展示和导出的所有字段
+     * @return array
+     */
+    public function getColumn() {
+        if (!$this->columns) {
+            $this->columns = [
+                'ID' => null,
+                'CREATED_AT' => [
+                    'header' => '创建时间',
+                    'value' => function ($row) {
+                        return (new DateTime([
+                            'value' => $row['CREATED_AT'],
+                        ]))->result();
+                    },
+                    'headerOther' => ['width' => '170'],
+                ],
+                'PERIOD_NUM' => '期数',
+                'CALC_MONTH' => '结算月',
+                'DEAL_TYPE_NAME' => [
+                    'header' => '交易类型',
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                'USER_NAME' => [
+                    'header' => '会员编号',
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'info', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                'REAL_NAME' => [
+                    'header' => '会员姓名',
+                    'headerOther' => [
+                        'width' => '120',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'success', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                'LAST_DEC_LV_NAME' => [
+                    'header' => '会员级别',
+                    'headerOther' => [
+                        'width' => '110',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                'LAST_EMP_LV_NAME' => [
+                    'header' => '聘级',
+                    'headerOther' => [
+                        'width' => '130',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                'IS_DEC' => [
+                    'header' => '是否报单中心',
+                    'value' => function ($row) {
+                        return (new YesNo([
+                            'value' => $row['IS_DEC'],
+                        ]))->result();
+                    },
+                    'headerOther' => function ($row) {
+                        return [
+                            'width' => '120',
+                        ];
+                    },
+                    'valueOther' => function ($row) {
+                        return [
+                            'tag' => ['type' => (isset($row['IS_DEC']) && $row['IS_DEC']) ? 'success' : 'info', 'size' => 'small']
+                        ];
+                    },
+                ],
+                'BEFORE_BALANCE' => [
+                    'header' => '交易前余额',
+                    'value' => function ($row) {
+                        return (new Price([
+                            'value' => $row['TOTAL'] - $row['AMOUNT'],
+                        ]))->result();
+                    },
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                'AMOUNT' => [
+                    'header' => '交易额',
+                    'value' => function ($row) {
+                        $result = (new Price([
+                            'value' => $row['AMOUNT'],
+                        ]))->result();
+                        return $row['IS_INCR'] > 0 ? '+' . $result : $result;
+                    },
+                    'headerOther' => [
+                        'width' => '150',
+                        'prop' => 'BONUS',
+                    ],
+                    'valueOther' => function ($row) {
+                        if ($row['IS_INCR'] > 0) {
+                            $type = 'success';
+                        } elseif ($row['IS_INCR'] == 0) {
+                            $type = 'danger';
+                        } else {
+                            $type = 'info';
+                        }
+                        return [
+                            'tag' => ['type' => $type, 'size' => 'small']
+                        ];
+                    },
+                ],
+                'TOTAL' => [
+                    'header' => '交易后余额',
+                    'value' => function ($row) {
+                        return (new Price([
+                            'value' => $row['TOTAL'],
+                        ]))->result();
+                    },
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                'ADMIN_NAME' => [
+                    'header' => '操作人',
+                    'headerOther' => ['width' => '110'],
+                ],
+                'REMARK' => [
+                    'header' => '备注',
+                    'headerOther' => ['width' => '250'],
+                ],
+                'ORDER_SN' => [
+                    'header' => '订单号',
+                    'headerOther' => ['width' => '250'],
+                ],
+            ];
+        }
+        return $this->columns;
+    }
+
+    /**
+     * 前台用于筛选的类型集合
+     * @return mixed
+     */
+    public function getFilterTypes() {
+        if (!$this->filterTypes) {
+            $this->filterTypes = [
+                'CREATED_AT' => ['isUserTable' => false, 'name' => '创建时间', 'other' => 'date'],
+                'PERIOD_NUM' => ['isUserTable' => false, 'name' => '期数'],
+                'CALC_MONTH' => ['isUserTable' => false, 'name' => '结算月', 'other' => 'month'],
+                'DEAL_TYPE_NAME' => ['isUserTable' => false, 'name' => '交易类型', 'other' => 'dealTypes'],
+                'USER_NAME' => ['isUserTable' => true, 'name' => '会员编号'],
+                'REAL_NAME' => ['isUserTable' => true, 'name' => '会员姓名'],
+                'LAST_DEC_LV_NAME' => ['isUserTable' => false, 'name' => '会员级别', 'other' => 'decLevel'],
+                'LAST_EMP_LV_NAME' => ['isUserTable' => false, 'name' => '聘级', 'other' => 'empLevel'],
+                'IS_DEC' => ['isUserTable' => true, 'name' => '是否报单中心', 'other' => 'yesOrNo'],
+                'AMOUNT' => ['isUserTable' => false, 'name' => '交易额'],
+                'TOTAL' => ['isUserTable' => false, 'name' => '交易后余额'],
+                'ADMIN_NAME' => ['isUserTable' => false, 'name' => '操作人'],
+                'REMARK' => ['isUserTable' => false, 'name' => '备注'],
+            ];
+        }
+        return $this->filterTypes;
+    }
+}

+ 212 - 208
backendApi/modules/v1/models/lists/bonus/FlowReconsumePointsList.php

@@ -1,208 +1,212 @@
-<?php
-
-namespace backendApi\modules\v1\models\lists\bonus;
-
-use common\helpers\Cache;
-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\DealType;
-use common\libs\dataList\column\DateTime;
-use common\models\FlowCF;
-use common\models\FlowReconsumePoints;
-use Yii;
-
-class FlowReconsumePointsList extends \common\libs\dataList\DataList implements DataListInterface {
-    /**
-     * 列表名称
-     * @return string
-     */
-    public function getListName() {
-        return '复消积分流水';
-    }
-
-    /**
-     * 列表筛选到的数据
-     * @throws \yii\base\Exception
-     */
-    public function dataHandle() {
-        $this->listData = FlowReconsumePoints::lists($this->condition, $this->params, [
-            'orderBy' => 'CREATED_AT DESC, ID DESC',
-            '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'] ?? '';
-            $this->listData['list'][$key]['LAST_STATUS_NAME'] = \Yii::$app->params['userStatus'][$value['LAST_STATUS']]['label'] ?? '';
-        }
-    }
-
-    /**
-     * 要展示和导出的所有字段
-     * @return array
-     */
-    public function getColumn() {
-        if (!$this->columns) {
-            $this->columns = [
-                'ID' => null,
-                'CREATED_AT' => [
-                    'header' => '创建时间',
-                    'value' => function ($row) {
-                        return (new DateTime([
-                            'value' => $row['CREATED_AT'],
-                        ]))->result();
-                    },
-                    'headerOther' => ['width' => '170'],
-                ],
-                'PERIOD_NUM' => '期数',
-                'CALC_MONTH' => '结算月',
-                'DEAL_TYPE_NAME' => [
-                    'header' => '交易类型',
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                ],
-                'USER_NAME' => [
-                    'header' => '会员编号',
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'info', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                'REAL_NAME' => [
-                    'header' => '会员姓名',
-                    'headerOther' => [
-                        'width' => '120',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'success', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                'LAST_DEC_LV_NAME' => [
-                    'header' => '会员级别',
-                    'headerOther' => [
-                        'width' => '110',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                'LAST_EMP_LV_NAME' => [
-                    'header' => '聘级',
-                    'headerOther' => [
-                        'width' => '130',
-                    ],
-                    'valueOther' => [
-                        'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
-                    ],
-                ],
-                'IS_DEC' => [
-                    'header' => '是否报单中心',
-                    'value' => function ($row) {
-                        return (new YesNo([
-                            'value' => $row['IS_DEC'],
-                        ]))->result();
-                    },
-                    'headerOther' => function ($row) {
-                        return [
-                            'width' => '120',
-                        ];
-                    },
-                    'valueOther' => function ($row) {
-                        return [
-                            'tag' => ['type' => (isset($row['IS_DEC']) && $row['IS_DEC']) ? 'success' : 'info', 'size' => 'small']
-                        ];
-                    },
-                ],
-                'BEFORE_BALANCE' => [
-                    'header' => '交易前余额',
-                    'value' => function ($row) {
-                        return (new Price([
-                            'value' => $row['TOTAL'] - $row['AMOUNT'],
-                        ]))->result();
-                    },
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                ],
-                'AMOUNT' => [
-                    'header' => '交易额',
-                    'value' => function ($row) {
-                        $result = (new Price([
-                            'value' => $row['AMOUNT'],
-                        ]))->result();
-                        return $row['IS_INCR'] > 0 ? '+' . $result : $result;
-                    },
-                    'headerOther' => [
-                        'width' => '150',
-                        'prop' => 'BONUS',
-                    ],
-                    'valueOther' => function ($row) {
-                        if ($row['IS_INCR'] > 0) {
-                            $type = 'success';
-                        } elseif ($row['IS_INCR'] == 0) {
-                            $type = 'danger';
-                        } else {
-                            $type = 'info';
-                        }
-                        return [
-                            'tag' => ['type' => $type, 'size' => 'small']
-                        ];
-                    },
-                ],
-                'TOTAL' => [
-                    'header' => '交易后余额',
-                    'value' => function ($row) {
-                        return (new Price([
-                            'value' => $row['TOTAL'],
-                        ]))->result();
-                    },
-                    'headerOther' => [
-                        'width' => '150',
-                    ],
-                ],
-                'ADMIN_NAME' => [
-                    'header' => '操作人',
-                    'headerOther' => ['width' => '110'],
-                ],
-                'REMARK' => [
-                    'header' => '备注',
-                    'headerOther' => ['width' => '250'],
-                ],
-            ];
-        }
-        return $this->columns;
-    }
-
-    /**
-     * 前台用于筛选的类型集合
-     * @return mixed
-     */
-    public function getFilterTypes() {
-        if (!$this->filterTypes) {
-            $this->filterTypes = [
-                'CREATED_AT' => ['isUserTable' => false, 'name' => '创建时间', 'other' => 'date'],
-                'PERIOD_NUM' => ['isUserTable' => false, 'name' => '期数'],
-                'CALC_MONTH' => ['isUserTable' => false, 'name' => '结算月', 'other' => 'month'],
-                'DEAL_TYPE_NAME' => ['isUserTable' => false, 'name' => '交易类型', 'other' => 'dealTypes'],
-                'USER_NAME' => ['isUserTable' => true, 'name' => '会员编号'],
-                'REAL_NAME' => ['isUserTable' => true, 'name' => '会员姓名'],
-                'LAST_DEC_LV_NAME' => ['isUserTable' => false, 'name' => '会员级别', 'other' => 'decLevel'],
-                'LAST_EMP_LV_NAME' => ['isUserTable' => false, 'name' => '聘级', 'other' => 'empLevel'],
-                'IS_DEC' => ['isUserTable' => true, 'name' => '是否报单中心', 'other' => 'yesOrNo'],
-                'AMOUNT' => ['isUserTable' => false, 'name' => '交易额'],
-                'TOTAL' => ['isUserTable' => false, 'name' => '交易后余额'],
-                'ADMIN_NAME' => ['isUserTable' => false, 'name' => '操作人'],
-                'REMARK' => ['isUserTable' => false, 'name' => '备注'],
-            ];
-        }
-        return $this->filterTypes;
-    }
-}
+<?php
+
+namespace backendApi\modules\v1\models\lists\bonus;
+
+use common\helpers\Cache;
+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\DealType;
+use common\libs\dataList\column\DateTime;
+use common\models\FlowCF;
+use common\models\FlowReconsumePoints;
+use Yii;
+
+class FlowReconsumePointsList extends \common\libs\dataList\DataList implements DataListInterface {
+    /**
+     * 列表名称
+     * @return string
+     */
+    public function getListName() {
+        return '复消积分流水';
+    }
+
+    /**
+     * 列表筛选到的数据
+     * @throws \yii\base\Exception
+     */
+    public function dataHandle() {
+        $this->listData = FlowReconsumePoints::lists($this->condition, $this->params, [
+            'orderBy' => 'CREATED_AT DESC, ID DESC',
+            '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'] ?? '';
+            $this->listData['list'][$key]['LAST_STATUS_NAME'] = \Yii::$app->params['userStatus'][$value['LAST_STATUS']]['label'] ?? '';
+        }
+    }
+
+    /**
+     * 要展示和导出的所有字段
+     * @return array
+     */
+    public function getColumn() {
+        if (!$this->columns) {
+            $this->columns = [
+                'ID' => null,
+                'CREATED_AT' => [
+                    'header' => '创建时间',
+                    'value' => function ($row) {
+                        return (new DateTime([
+                            'value' => $row['CREATED_AT'],
+                        ]))->result();
+                    },
+                    'headerOther' => ['width' => '170'],
+                ],
+                'PERIOD_NUM' => '期数',
+                'CALC_MONTH' => '结算月',
+                'DEAL_TYPE_NAME' => [
+                    'header' => '交易类型',
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                'USER_NAME' => [
+                    'header' => '会员编号',
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'info', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                'REAL_NAME' => [
+                    'header' => '会员姓名',
+                    'headerOther' => [
+                        'width' => '120',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'success', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                'LAST_DEC_LV_NAME' => [
+                    'header' => '会员级别',
+                    'headerOther' => [
+                        'width' => '110',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                'LAST_EMP_LV_NAME' => [
+                    'header' => '聘级',
+                    'headerOther' => [
+                        'width' => '130',
+                    ],
+                    'valueOther' => [
+                        'tag' => ['type' => 'warning', 'size' => 'small', 'class' => 'no-border']
+                    ],
+                ],
+                'IS_DEC' => [
+                    'header' => '是否报单中心',
+                    'value' => function ($row) {
+                        return (new YesNo([
+                            'value' => $row['IS_DEC'],
+                        ]))->result();
+                    },
+                    'headerOther' => function ($row) {
+                        return [
+                            'width' => '120',
+                        ];
+                    },
+                    'valueOther' => function ($row) {
+                        return [
+                            'tag' => ['type' => (isset($row['IS_DEC']) && $row['IS_DEC']) ? 'success' : 'info', 'size' => 'small']
+                        ];
+                    },
+                ],
+                'BEFORE_BALANCE' => [
+                    'header' => '交易前余额',
+                    'value' => function ($row) {
+                        return (new Price([
+                            'value' => $row['TOTAL'] - $row['AMOUNT'],
+                        ]))->result();
+                    },
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                'AMOUNT' => [
+                    'header' => '交易额',
+                    'value' => function ($row) {
+                        $result = (new Price([
+                            'value' => $row['AMOUNT'],
+                        ]))->result();
+                        return $row['IS_INCR'] > 0 ? '+' . $result : $result;
+                    },
+                    'headerOther' => [
+                        'width' => '150',
+                        'prop' => 'BONUS',
+                    ],
+                    'valueOther' => function ($row) {
+                        if ($row['IS_INCR'] > 0) {
+                            $type = 'success';
+                        } elseif ($row['IS_INCR'] == 0) {
+                            $type = 'danger';
+                        } else {
+                            $type = 'info';
+                        }
+                        return [
+                            'tag' => ['type' => $type, 'size' => 'small']
+                        ];
+                    },
+                ],
+                'TOTAL' => [
+                    'header' => '交易后余额',
+                    'value' => function ($row) {
+                        return (new Price([
+                            'value' => $row['TOTAL'],
+                        ]))->result();
+                    },
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                'ADMIN_NAME' => [
+                    'header' => '操作人',
+                    'headerOther' => ['width' => '110'],
+                ],
+                'REMARK' => [
+                    'header' => '备注',
+                    'headerOther' => ['width' => '250'],
+                ],
+                'ORDER_SN' => [
+                    'header' => '订单号',
+                    'headerOther' => ['width' => '250'],
+                ],
+            ];
+        }
+        return $this->columns;
+    }
+
+    /**
+     * 前台用于筛选的类型集合
+     * @return mixed
+     */
+    public function getFilterTypes() {
+        if (!$this->filterTypes) {
+            $this->filterTypes = [
+                'CREATED_AT' => ['isUserTable' => false, 'name' => '创建时间', 'other' => 'date'],
+                'PERIOD_NUM' => ['isUserTable' => false, 'name' => '期数'],
+                'CALC_MONTH' => ['isUserTable' => false, 'name' => '结算月', 'other' => 'month'],
+                'DEAL_TYPE_NAME' => ['isUserTable' => false, 'name' => '交易类型', 'other' => 'dealTypes'],
+                'USER_NAME' => ['isUserTable' => true, 'name' => '会员编号'],
+                'REAL_NAME' => ['isUserTable' => true, 'name' => '会员姓名'],
+                'LAST_DEC_LV_NAME' => ['isUserTable' => false, 'name' => '会员级别', 'other' => 'decLevel'],
+                'LAST_EMP_LV_NAME' => ['isUserTable' => false, 'name' => '聘级', 'other' => 'empLevel'],
+                'IS_DEC' => ['isUserTable' => true, 'name' => '是否报单中心', 'other' => 'yesOrNo'],
+                'AMOUNT' => ['isUserTable' => false, 'name' => '交易额'],
+                'TOTAL' => ['isUserTable' => false, 'name' => '交易后余额'],
+                'ADMIN_NAME' => ['isUserTable' => false, 'name' => '操作人'],
+                'REMARK' => ['isUserTable' => false, 'name' => '备注'],
+            ];
+        }
+        return $this->filterTypes;
+    }
+}

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

@@ -0,0 +1,91 @@
+<?php
+namespace backendApi\modules\v1\models\lists\shop;
+
+use common\libs\dataList\DataListInterface;
+use common\models\Order;
+use common\models\OrderPeriodAdjust;
+use common\libs\dataList\column\DateTime;
+
+class OrderPeriodAdjustList extends \common\libs\dataList\DataList implements DataListInterface
+{
+    /**
+     * 列表名称
+     * @return string
+     */
+    public function getListName(){
+        return '订单期数调整列表';
+    }
+
+    /**
+     * 列表筛选到的数据
+     */
+    public function dataHandle()
+    {
+        $this->listData = OrderPeriodAdjust::lists($this->condition, $this->params, [
+            'select' => 'P.*,O.ORDER_TYPE',
+            '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'],
+            ],
+            'page' => $this->page,
+            'pageSize' => $this->pageSize,
+        ]);
+    }
+
+    /**
+     * 要展示和导出的所有字段
+     * @return array
+     */
+    public function getColumn(){
+        if (!$this->columns) {
+            $this->columns = [
+                'ID' => null,
+                'ORDER_SN' => [
+                    'header' => '订单号',
+                ],
+                'ORDER_TYPE' => [
+                    'header' => '订单类型',
+                    'value' => function ($row) {
+                        return $row['ORDER_TYPE'] == 'ZC' ? '首单' : '复消';
+                    },
+                ],
+                'ORIGIN_PERIOD' => [
+                    'header' => '调整前期数',
+                ],
+                'MODERN_PERIOD' => [
+                    'header' => '调整后期数',
+                ],
+                'CREATED_AT' => [
+                    'header' => '调整时间',
+                    'value' => function ($row) {
+                        return (new DateTime([
+                            'value' => $row['CREATED_AT'],
+                        ]))->result();
+                    },
+                ],
+                'ADMIN_ID' => [
+                    'header' => '操作人',
+                ],
+            ];
+        }
+        return $this->columns;
+    }
+
+    /**
+     * 前台用于筛选的类型集合
+     * @return mixed
+     */
+    public function getFilterTypes()
+    {
+        if (!$this->filterTypes) {
+            $this->filterTypes = [
+                'ORDER_SN' => ['name'=> '订单号'],
+                'ORIGIN_PERIOD'=> ['name'=> '调整前期数'],
+                'MODERN_PERIOD'=> ['name'=> '调整后期数'],
+                'CREATED_AT'=> ['name'=> '调整时间', 'other'=>'date'],
+            ];
+        }
+        return $this->filterTypes;
+    }
+}

+ 978 - 977
common/helpers/user/Balance.php

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

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

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

+ 84 - 83
common/models/FlowExchangePoints.php

@@ -1,83 +1,84 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%FLOW_RECONSUME_POINTS}}".
- *
- * @property string $ID
- * @property string $USER_ID 会员ID
- * @property string $LAST_DEC_LV 记录时会员级别
- * @property string $LAST_EMP_LV 记录时会员聘级
- * @property int $LAST_STATUS 记录时状态
- * @property string $AMOUNT 金额
- * @property string $AMOUNT_STANDARD 标准金额
- * @property string $TOTAL 当前总金额
- * @property int $IS_INCR 是否增加
- * @property string $REMARK 备注
- * @property int $REMARK_IS_SHOW 备注是否显示
- * @property string $DEAL_TYPE_ID 交易类型名称
- * @property int $DEAL_TYPE_IS_PRESET 交易类型是否预置
- * @property string $ADMIN_NAME 操作人名称
- * @property int $PERIOD_NUM 所在期数
- * @property int $CALC_MONTH 所在结算月
- * @property string $P_MONTH 表分区的日期索引
- * @property int $CREATED_AT 创建时间
- * @property int $DELETED 是否删除
- * @property int $DELETED_AT 删除时间
- */
-class FlowExchangePoints extends \common\components\ActiveRecord
-{
-    /**
-     * {@inheritdoc}
-     */
-    public static function tableName()
-    {
-        return '{{%FLOW_EXCHANGE_POINTS}}';
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function rules()
-    {
-        return [
-            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
-            [['AMOUNT', 'TOTAL', 'AMOUNT_STANDARD'], 'number'],
-            [['LAST_STATUS', 'IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'REMARK_IS_SHOW', 'DELETED', 'DELETED_AT', 'DEAL_TYPE_IS_PRESET'], 'integer'],
-            [['ID', 'USER_ID', 'ADMIN_NAME', 'LAST_DEC_LV', 'LAST_EMP_LV', 'DEAL_TYPE_ID'], 'string', 'max' => 32],
-            [['REMARK'], 'string', 'max' => 255],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'USER_ID' => '会员ID',
-            'LAST_DEC_LV' => '记录时会员级别',
-            'LAST_EMP_LV' => '记录时会员聘级',
-            'LAST_STATUS' => '记录时状态',
-            'AMOUNT' => '金额',
-            'TOTAL' => '当前总金额',
-            'IS_INCR' => '是否增加',
-            'REMARK' => '备注',
-            'REMARK_IS_SHOW' => '备注是否显示',
-            'DEAL_TYPE_ID' => '交易类型ID',
-            'DEAL_TYPE_IS_PRESET' => '交易类型是否预置',
-            'ADMIN_NAME' => '操作人名称',
-            'PERIOD_NUM' => '所在期数',
-            'CALC_MONTH' => '所在结算月',
-            'P_MONTH' => '表分区的日期索引',
-            'CREATED_AT' => '创建时间',
-            'DELETED' => '是否删除',
-            'DELETED_AT' => '删除时间',
-        ];
-    }
-}
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%FLOW_RECONSUME_POINTS}}".
+ *
+ * @property string $ID
+ * @property string $USER_ID 会员ID
+ * @property string $LAST_DEC_LV 记录时会员级别
+ * @property string $LAST_EMP_LV 记录时会员聘级
+ * @property int $LAST_STATUS 记录时状态
+ * @property string $AMOUNT 金额
+ * @property string $AMOUNT_STANDARD 标准金额
+ * @property string $TOTAL 当前总金额
+ * @property int $IS_INCR 是否增加
+ * @property string $REMARK 备注
+ * @property int $REMARK_IS_SHOW 备注是否显示
+ * @property string $DEAL_TYPE_ID 交易类型名称
+ * @property int $DEAL_TYPE_IS_PRESET 交易类型是否预置
+ * @property string $ADMIN_NAME 操作人名称
+ * @property int $PERIOD_NUM 所在期数
+ * @property int $CALC_MONTH 所在结算月
+ * @property string $P_MONTH 表分区的日期索引
+ * @property int $CREATED_AT 创建时间
+ * @property int $DELETED 是否删除
+ * @property int $DELETED_AT 删除时间
+ */
+class FlowExchangePoints extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%FLOW_EXCHANGE_POINTS}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
+            [['AMOUNT', 'TOTAL', 'AMOUNT_STANDARD'], 'number'],
+            [['LAST_STATUS', 'IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'REMARK_IS_SHOW', 'DELETED', 'DELETED_AT', 'DEAL_TYPE_IS_PRESET'], 'integer'],
+            [['ID', 'USER_ID', 'ADMIN_NAME', 'LAST_DEC_LV', 'LAST_EMP_LV', 'DEAL_TYPE_ID'], 'string', 'max' => 32],
+            [['REMARK'], 'string', 'max' => 255],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '会员ID',
+            'LAST_DEC_LV' => '记录时会员级别',
+            'LAST_EMP_LV' => '记录时会员聘级',
+            'LAST_STATUS' => '记录时状态',
+            'AMOUNT' => '金额',
+            'TOTAL' => '当前总金额',
+            'IS_INCR' => '是否增加',
+            'REMARK' => '备注',
+            'REMARK_IS_SHOW' => '备注是否显示',
+            'DEAL_TYPE_ID' => '交易类型ID',
+            'DEAL_TYPE_IS_PRESET' => '交易类型是否预置',
+            'ADMIN_NAME' => '操作人名称',
+            'PERIOD_NUM' => '所在期数',
+            'CALC_MONTH' => '所在结算月',
+            'P_MONTH' => '表分区的日期索引',
+            'CREATED_AT' => '创建时间',
+            'DELETED' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'ORDER_SN' => '订单号',
+        ];
+    }
+}

+ 82 - 81
common/models/FlowGaragePoints.php

@@ -1,81 +1,82 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%FLOW_GARAGE_POINTS}}".
- *
- * @property string $ID
- * @property string $USER_ID 会员ID
- * @property string $CALC_ID 奖金结算表ID
- * @property string $AMOUNT 金额
- * @property string $TOTAL 当前总金额
- * @property int $IS_INCR 是否增加
- * @property string $REMARK 备注
- * @property string $ADMIN_NAME 操作人名称
- * @property int $PERIOD_NUM 所在期数
- * @property int $CALC_MONTH 所在结算月
- * @property string $P_MONTH 表分区的日期索引
- * @property int $CREATED_AT 创建时间
- * @property int $DELETED 是否删除
- * @property int $DELETED_AT 删除时间
- * @property int $SORT 排序
- * @property string $TRANSFER_SN 转账流水号
- */
-class FlowGaragePoints extends \common\components\ActiveRecord
-{
-    const INCR_REDUCE = 0;      // 减少
-    const INCR_ADD = 1;         // 增加
-    const INCR_FREEZE = 2;      // 冻结
-    const INCR_UNFREEZE = 3;    // 解冻
-
-    /**
-     * @inheritdoc
-     */
-    public static function tableName()
-    {
-        return '{{%FLOW_GARAGE_POINTS}}';
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
-            [['AMOUNT', 'TOTAL'], 'number'],
-            [['IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'DELETED', 'DELETED_AT', 'SORT'], 'integer'],
-            [['ID', 'USER_ID', 'CALC_ID', 'ADMIN_NAME', 'TRANSFER_SN', 'LAST_CROWN_LV'], 'string', 'max' => 32],
-            [['REMARK'], 'string', 'max' => 255],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'USER_ID' => '会员ID',
-            'CALC_ID' => '结算表ID',
-            'AMOUNT' => '交易金额',
-            'TOTAL' => '当前总金额',
-            'IS_INCR' => '是否增加',
-            'REMARK' => '备注',
-            'ADMIN_NAME' => '操作人名称',
-            'PERIOD_NUM' => '所在期数',
-            'CALC_MONTH' => '所在结算月',
-            'P_MONTH' => '表分区的日期索引',
-            'CREATED_AT' => '创建时间',
-            'DELETED' => '是否删除',
-            'DELETED_AT' => '删除时间',
-            'SORT' => '排序',
-            'TRANSFER_SN' => '转账流水号',
-        ];
-    }
-}
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%FLOW_GARAGE_POINTS}}".
+ *
+ * @property string $ID
+ * @property string $USER_ID 会员ID
+ * @property string $CALC_ID 奖金结算表ID
+ * @property string $AMOUNT 金额
+ * @property string $TOTAL 当前总金额
+ * @property int $IS_INCR 是否增加
+ * @property string $REMARK 备注
+ * @property string $ADMIN_NAME 操作人名称
+ * @property int $PERIOD_NUM 所在期数
+ * @property int $CALC_MONTH 所在结算月
+ * @property string $P_MONTH 表分区的日期索引
+ * @property int $CREATED_AT 创建时间
+ * @property int $DELETED 是否删除
+ * @property int $DELETED_AT 删除时间
+ * @property int $SORT 排序
+ * @property string $TRANSFER_SN 转账流水号
+ */
+class FlowGaragePoints extends \common\components\ActiveRecord
+{
+    const INCR_REDUCE = 0;      // 减少
+    const INCR_ADD = 1;         // 增加
+    const INCR_FREEZE = 2;      // 冻结
+    const INCR_UNFREEZE = 3;    // 解冻
+
+    /**
+     * @inheritdoc
+     */
+    public static function tableName()
+    {
+        return '{{%FLOW_GARAGE_POINTS}}';
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
+            [['AMOUNT', 'TOTAL'], 'number'],
+            [['IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'DELETED', 'DELETED_AT', 'SORT'], 'integer'],
+            [['ID', 'USER_ID', 'CALC_ID', 'ADMIN_NAME', 'TRANSFER_SN', 'LAST_CROWN_LV'], 'string', 'max' => 32],
+            [['REMARK'], 'string', 'max' => 255],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '会员ID',
+            'CALC_ID' => '结算表ID',
+            'AMOUNT' => '交易金额',
+            'TOTAL' => '当前总金额',
+            'IS_INCR' => '是否增加',
+            'REMARK' => '备注',
+            'ADMIN_NAME' => '操作人名称',
+            'PERIOD_NUM' => '所在期数',
+            'CALC_MONTH' => '所在结算月',
+            'P_MONTH' => '表分区的日期索引',
+            'CREATED_AT' => '创建时间',
+            'DELETED' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'SORT' => '排序',
+            'TRANSFER_SN' => '转账流水号',
+            'ORDER_SN' => '订单号',
+        ];
+    }
+}

+ 83 - 82
common/models/FlowReconsumePoints.php

@@ -1,82 +1,83 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%FLOW_RECONSUME_POINTS}}".
- *
- * @property string $ID
- * @property string $USER_ID 会员ID
- * @property string $LAST_DEC_LV 记录时会员级别
- * @property string $LAST_EMP_LV 记录时会员聘级
- * @property int $LAST_STATUS 记录时状态
- * @property string $AMOUNT 金额
- * @property string $TOTAL 当前总金额
- * @property int $IS_INCR 是否增加
- * @property string $REMARK 备注
- * @property int $REMARK_IS_SHOW 备注是否显示
- * @property string $DEAL_TYPE_ID 交易类型名称
- * @property int $DEAL_TYPE_IS_PRESET 交易类型是否预置
- * @property string $ADMIN_NAME 操作人名称
- * @property int $PERIOD_NUM 所在期数
- * @property int $CALC_MONTH 所在结算月
- * @property string $P_MONTH 表分区的日期索引
- * @property int $CREATED_AT 创建时间
- * @property int $DELETED 是否删除
- * @property int $DELETED_AT 删除时间
- */
-class FlowReconsumePoints extends \common\components\ActiveRecord
-{
-    /**
-     * {@inheritdoc}
-     */
-    public static function tableName()
-    {
-        return '{{%FLOW_RECONSUME_POINTS}}';
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function rules()
-    {
-        return [
-            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
-            [['AMOUNT', 'TOTAL'], 'number'],
-            [['LAST_STATUS', 'IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'REMARK_IS_SHOW', 'DELETED', 'DELETED_AT', 'DEAL_TYPE_IS_PRESET'], 'integer'],
-            [['ID', 'USER_ID', 'ADMIN_NAME', 'LAST_DEC_LV', 'LAST_EMP_LV', 'DEAL_TYPE_ID'], 'string', 'max' => 32],
-            [['REMARK'], 'string', 'max' => 255],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'USER_ID' => '会员ID',
-            'LAST_DEC_LV' => '记录时会员级别',
-            'LAST_EMP_LV' => '记录时会员聘级',
-            'LAST_STATUS' => '记录时状态',
-            'AMOUNT' => '金额',
-            'TOTAL' => '当前总金额',
-            'IS_INCR' => '是否增加',
-            'REMARK' => '备注',
-            'REMARK_IS_SHOW' => '备注是否显示',
-            'DEAL_TYPE_ID' => '交易类型ID',
-            'DEAL_TYPE_IS_PRESET' => '交易类型是否预置',
-            'ADMIN_NAME' => '操作人名称',
-            'PERIOD_NUM' => '所在期数',
-            'CALC_MONTH' => '所在结算月',
-            'P_MONTH' => '表分区的日期索引',
-            'CREATED_AT' => '创建时间',
-            'DELETED' => '是否删除',
-            'DELETED_AT' => '删除时间',
-        ];
-    }
-}
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%FLOW_RECONSUME_POINTS}}".
+ *
+ * @property string $ID
+ * @property string $USER_ID 会员ID
+ * @property string $LAST_DEC_LV 记录时会员级别
+ * @property string $LAST_EMP_LV 记录时会员聘级
+ * @property int $LAST_STATUS 记录时状态
+ * @property string $AMOUNT 金额
+ * @property string $TOTAL 当前总金额
+ * @property int $IS_INCR 是否增加
+ * @property string $REMARK 备注
+ * @property int $REMARK_IS_SHOW 备注是否显示
+ * @property string $DEAL_TYPE_ID 交易类型名称
+ * @property int $DEAL_TYPE_IS_PRESET 交易类型是否预置
+ * @property string $ADMIN_NAME 操作人名称
+ * @property int $PERIOD_NUM 所在期数
+ * @property int $CALC_MONTH 所在结算月
+ * @property string $P_MONTH 表分区的日期索引
+ * @property int $CREATED_AT 创建时间
+ * @property int $DELETED 是否删除
+ * @property int $DELETED_AT 删除时间
+ */
+class FlowReconsumePoints extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%FLOW_RECONSUME_POINTS}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
+            [['AMOUNT', 'TOTAL'], 'number'],
+            [['LAST_STATUS', 'IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'REMARK_IS_SHOW', 'DELETED', 'DELETED_AT', 'DEAL_TYPE_IS_PRESET'], 'integer'],
+            [['ID', 'USER_ID', 'ADMIN_NAME', 'LAST_DEC_LV', 'LAST_EMP_LV', 'DEAL_TYPE_ID'], 'string', 'max' => 32],
+            [['REMARK'], 'string', 'max' => 255],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '会员ID',
+            'LAST_DEC_LV' => '记录时会员级别',
+            'LAST_EMP_LV' => '记录时会员聘级',
+            'LAST_STATUS' => '记录时状态',
+            'AMOUNT' => '金额',
+            'TOTAL' => '当前总金额',
+            'IS_INCR' => '是否增加',
+            'REMARK' => '备注',
+            'REMARK_IS_SHOW' => '备注是否显示',
+            'DEAL_TYPE_ID' => '交易类型ID',
+            'DEAL_TYPE_IS_PRESET' => '交易类型是否预置',
+            'ADMIN_NAME' => '操作人名称',
+            'PERIOD_NUM' => '所在期数',
+            'CALC_MONTH' => '所在结算月',
+            'P_MONTH' => '表分区的日期索引',
+            'CREATED_AT' => '创建时间',
+            'DELETED' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'ORDER_SN' => '订单号',
+        ];
+    }
+}

+ 82 - 81
common/models/FlowTourismPoints.php

@@ -1,81 +1,82 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%FLOW_TOURISM_POINTS}}".
- *
- * @property string $ID
- * @property string $USER_ID 会员ID
- * @property string $CALC_ID 奖金结算表ID
- * @property string $AMOUNT 金额
- * @property string $TOTAL 当前总金额
- * @property int $IS_INCR 是否增加
- * @property string $REMARK 备注
- * @property string $ADMIN_NAME 操作人名称
- * @property int $PERIOD_NUM 所在期数
- * @property int $CALC_MONTH 所在结算月
- * @property string $P_MONTH 表分区的日期索引
- * @property int $CREATED_AT 创建时间
- * @property int $DELETED 是否删除
- * @property int $DELETED_AT 删除时间
- * @property int $SORT 排序
- * @property string $TRANSFER_SN 转账流水号
- */
-class FlowTourismPoints extends \common\components\ActiveRecord
-{
-    const INCR_REDUCE = 0;      // 减少
-    const INCR_ADD = 1;         // 增加
-    const INCR_FREEZE = 2;      // 冻结
-    const INCR_UNFREEZE = 3;    // 解冻
-
-    /**
-     * @inheritdoc
-     */
-    public static function tableName()
-    {
-        return '{{%FLOW_TOURISM_POINTS}}';
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
-            [['AMOUNT', 'TOTAL'], 'number'],
-            [['IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'DELETED', 'DELETED_AT', 'SORT'], 'integer'],
-            [['ID', 'USER_ID', 'CALC_ID', 'ADMIN_NAME', 'TRANSFER_SN', 'LAST_CROWN_LV'], 'string', 'max' => 32],
-            [['REMARK'], 'string', 'max' => 255],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'USER_ID' => '会员ID',
-            'CALC_ID' => '结算表ID',
-            'AMOUNT' => '交易金额',
-            'TOTAL' => '当前总金额',
-            'IS_INCR' => '是否增加',
-            'REMARK' => '备注',
-            'ADMIN_NAME' => '操作人名称',
-            'PERIOD_NUM' => '所在期数',
-            'CALC_MONTH' => '所在结算月',
-            'P_MONTH' => '表分区的日期索引',
-            'CREATED_AT' => '创建时间',
-            'DELETED' => '是否删除',
-            'DELETED_AT' => '删除时间',
-            'SORT' => '排序',
-            'TRANSFER_SN' => '转账流水号',
-        ];
-    }
-}
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%FLOW_TOURISM_POINTS}}".
+ *
+ * @property string $ID
+ * @property string $USER_ID 会员ID
+ * @property string $CALC_ID 奖金结算表ID
+ * @property string $AMOUNT 金额
+ * @property string $TOTAL 当前总金额
+ * @property int $IS_INCR 是否增加
+ * @property string $REMARK 备注
+ * @property string $ADMIN_NAME 操作人名称
+ * @property int $PERIOD_NUM 所在期数
+ * @property int $CALC_MONTH 所在结算月
+ * @property string $P_MONTH 表分区的日期索引
+ * @property int $CREATED_AT 创建时间
+ * @property int $DELETED 是否删除
+ * @property int $DELETED_AT 删除时间
+ * @property int $SORT 排序
+ * @property string $TRANSFER_SN 转账流水号
+ */
+class FlowTourismPoints extends \common\components\ActiveRecord
+{
+    const INCR_REDUCE = 0;      // 减少
+    const INCR_ADD = 1;         // 增加
+    const INCR_FREEZE = 2;      // 冻结
+    const INCR_UNFREEZE = 3;    // 解冻
+
+    /**
+     * @inheritdoc
+     */
+    public static function tableName()
+    {
+        return '{{%FLOW_TOURISM_POINTS}}';
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
+            [['AMOUNT', 'TOTAL'], 'number'],
+            [['IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'DELETED', 'DELETED_AT', 'SORT'], 'integer'],
+            [['ID', 'USER_ID', 'CALC_ID', 'ADMIN_NAME', 'TRANSFER_SN', 'LAST_CROWN_LV'], 'string', 'max' => 32],
+            [['REMARK'], 'string', 'max' => 255],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '会员ID',
+            'CALC_ID' => '结算表ID',
+            'AMOUNT' => '交易金额',
+            'TOTAL' => '当前总金额',
+            'IS_INCR' => '是否增加',
+            'REMARK' => '备注',
+            'ADMIN_NAME' => '操作人名称',
+            'PERIOD_NUM' => '所在期数',
+            'CALC_MONTH' => '所在结算月',
+            'P_MONTH' => '表分区的日期索引',
+            'CREATED_AT' => '创建时间',
+            'DELETED' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'SORT' => '排序',
+            'TRANSFER_SN' => '转账流水号',
+            'ORDER_SN' => '订单号',
+        ];
+    }
+}

+ 82 - 81
common/models/FlowVillaPoints.php

@@ -1,81 +1,82 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%FLOW_VILLA_POINTS}}".
- *
- * @property string $ID
- * @property string $USER_ID 会员ID
- * @property string $CALC_ID 奖金结算表ID
- * @property string $AMOUNT 金额
- * @property string $TOTAL 当前总金额
- * @property int $IS_INCR 是否增加
- * @property string $REMARK 备注
- * @property string $ADMIN_NAME 操作人名称
- * @property int $PERIOD_NUM 所在期数
- * @property int $CALC_MONTH 所在结算月
- * @property string $P_MONTH 表分区的日期索引
- * @property int $CREATED_AT 创建时间
- * @property int $DELETED 是否删除
- * @property int $DELETED_AT 删除时间
- * @property int $SORT 排序
- * @property string $TRANSFER_SN 转账流水号
- */
-class FlowVillaPoints extends \common\components\ActiveRecord
-{
-    const INCR_REDUCE = 0;      // 减少
-    const INCR_ADD = 1;         // 增加
-    const INCR_FREEZE = 2;      // 冻结
-    const INCR_UNFREEZE = 3;    // 解冻
-
-    /**
-     * @inheritdoc
-     */
-    public static function tableName()
-    {
-        return '{{%FLOW_VILLA_POINTS}}';
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
-            [['AMOUNT', 'TOTAL'], 'number'],
-            [['IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'DELETED', 'DELETED_AT', 'SORT'], 'integer'],
-            [['ID', 'USER_ID', 'CALC_ID', 'ADMIN_NAME', 'TRANSFER_SN', 'LAST_CROWN_LV'], 'string', 'max' => 32],
-            [['REMARK'], 'string', 'max' => 255],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'USER_ID' => '会员ID',
-            'CALC_ID' => '结算表ID',
-            'AMOUNT' => '交易金额',
-            'TOTAL' => '当前总金额',
-            'IS_INCR' => '是否增加',
-            'REMARK' => '备注',
-            'ADMIN_NAME' => '操作人名称',
-            'PERIOD_NUM' => '所在期数',
-            'CALC_MONTH' => '所在结算月',
-            'P_MONTH' => '表分区的日期索引',
-            'CREATED_AT' => '创建时间',
-            'DELETED' => '是否删除',
-            'DELETED_AT' => '删除时间',
-            'SORT' => '排序',
-            'TRANSFER_SN' => '转账流水号',
-        ];
-    }
-}
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%FLOW_VILLA_POINTS}}".
+ *
+ * @property string $ID
+ * @property string $USER_ID 会员ID
+ * @property string $CALC_ID 奖金结算表ID
+ * @property string $AMOUNT 金额
+ * @property string $TOTAL 当前总金额
+ * @property int $IS_INCR 是否增加
+ * @property string $REMARK 备注
+ * @property string $ADMIN_NAME 操作人名称
+ * @property int $PERIOD_NUM 所在期数
+ * @property int $CALC_MONTH 所在结算月
+ * @property string $P_MONTH 表分区的日期索引
+ * @property int $CREATED_AT 创建时间
+ * @property int $DELETED 是否删除
+ * @property int $DELETED_AT 删除时间
+ * @property int $SORT 排序
+ * @property string $TRANSFER_SN 转账流水号
+ */
+class FlowVillaPoints extends \common\components\ActiveRecord
+{
+    const INCR_REDUCE = 0;      // 减少
+    const INCR_ADD = 1;         // 增加
+    const INCR_FREEZE = 2;      // 冻结
+    const INCR_UNFREEZE = 3;    // 解冻
+
+    /**
+     * @inheritdoc
+     */
+    public static function tableName()
+    {
+        return '{{%FLOW_VILLA_POINTS}}';
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
+            [['AMOUNT', 'TOTAL'], 'number'],
+            [['IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'DELETED', 'DELETED_AT', 'SORT'], 'integer'],
+            [['ID', 'USER_ID', 'CALC_ID', 'ADMIN_NAME', 'TRANSFER_SN', 'LAST_CROWN_LV'], 'string', 'max' => 32],
+            [['REMARK'], 'string', 'max' => 255],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '会员ID',
+            'CALC_ID' => '结算表ID',
+            'AMOUNT' => '交易金额',
+            'TOTAL' => '当前总金额',
+            'IS_INCR' => '是否增加',
+            'REMARK' => '备注',
+            'ADMIN_NAME' => '操作人名称',
+            'PERIOD_NUM' => '所在期数',
+            'CALC_MONTH' => '所在结算月',
+            'P_MONTH' => '表分区的日期索引',
+            'CREATED_AT' => '创建时间',
+            'DELETED' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'SORT' => '排序',
+            'TRANSFER_SN' => '转账流水号',
+            'ORDER_SN' => '订单号',
+        ];
+    }
+}

+ 82 - 81
common/models/FlowWallet.php

@@ -1,81 +1,82 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%FLOW_WALLET}}".
- *
- * @property string $ID
- * @property string $USER_ID 会员ID
- * @property string $CALC_ID 奖金结算表ID
- * @property string $AMOUNT 金额
- * @property string $TOTAL 当前总金额
- * @property int $IS_INCR 是否增加
- * @property string $REMARK 备注
- * @property string $ADMIN_NAME 操作人名称
- * @property int $PERIOD_NUM 所在期数
- * @property int $CALC_MONTH 所在结算月
- * @property string $P_MONTH 表分区的日期索引
- * @property int $CREATED_AT 创建时间
- * @property int $DELETED 是否删除
- * @property int $DELETED_AT 删除时间
- * @property int $SORT 排序
- * @property string $TRANSFER_SN 转账流水号
- */
-class FlowWallet extends \common\components\ActiveRecord
-{
-    const INCR_REDUCE = 0;      // 减少
-    const INCR_ADD = 1;         // 增加
-    const INCR_FREEZE = 2;      // 冻结
-    const INCR_UNFREEZE = 3;    // 解冻
-
-    /**
-     * @inheritdoc
-     */
-    public static function tableName()
-    {
-        return '{{%FLOW_WALLET}}';
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
-            [['AMOUNT', 'TOTAL'], 'number'],
-            [['IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'DELETED', 'DELETED_AT', 'SORT'], 'integer'],
-            [['ID', 'USER_ID', 'CALC_ID', 'ADMIN_NAME', 'TRANSFER_SN'], 'string', 'max' => 32],
-            [['REMARK'], 'string', 'max' => 255],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'USER_ID' => '会员ID',
-            'CALC_ID' => '现金结算表ID',
-            'AMOUNT' => '金额',
-            'TOTAL' => '当前总金额',
-            'IS_INCR' => '是否增加',
-            'REMARK' => '备注',
-            'ADMIN_NAME' => '操作人名称',
-            'PERIOD_NUM' => '所在期数',
-            'CALC_MONTH' => '所在结算月',
-            'P_MONTH' => '表分区的日期索引',
-            'CREATED_AT' => '创建时间',
-            'DELETED' => '是否删除',
-            'DELETED_AT' => '删除时间',
-            'SORT' => '排序',
-            'TRANSFER_SN' => '转账流水号',
-        ];
-    }
-}
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%FLOW_WALLET}}".
+ *
+ * @property string $ID
+ * @property string $USER_ID 会员ID
+ * @property string $CALC_ID 奖金结算表ID
+ * @property string $AMOUNT 金额
+ * @property string $TOTAL 当前总金额
+ * @property int $IS_INCR 是否增加
+ * @property string $REMARK 备注
+ * @property string $ADMIN_NAME 操作人名称
+ * @property int $PERIOD_NUM 所在期数
+ * @property int $CALC_MONTH 所在结算月
+ * @property string $P_MONTH 表分区的日期索引
+ * @property int $CREATED_AT 创建时间
+ * @property int $DELETED 是否删除
+ * @property int $DELETED_AT 删除时间
+ * @property int $SORT 排序
+ * @property string $TRANSFER_SN 转账流水号
+ */
+class FlowWallet extends \common\components\ActiveRecord
+{
+    const INCR_REDUCE = 0;      // 减少
+    const INCR_ADD = 1;         // 增加
+    const INCR_FREEZE = 2;      // 冻结
+    const INCR_UNFREEZE = 3;    // 解冻
+
+    /**
+     * @inheritdoc
+     */
+    public static function tableName()
+    {
+        return '{{%FLOW_WALLET}}';
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'REMARK', 'PERIOD_NUM', 'CALC_MONTH', 'P_MONTH', 'CREATED_AT'], 'required'],
+            [['AMOUNT', 'TOTAL'], 'number'],
+            [['IS_INCR', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'DELETED', 'DELETED_AT', 'SORT'], 'integer'],
+            [['ID', 'USER_ID', 'CALC_ID', 'ADMIN_NAME', 'TRANSFER_SN'], 'string', 'max' => 32],
+            [['REMARK'], 'string', 'max' => 255],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '会员ID',
+            'CALC_ID' => '现金结算表ID',
+            'AMOUNT' => '金额',
+            'TOTAL' => '当前总金额',
+            'IS_INCR' => '是否增加',
+            'REMARK' => '备注',
+            'ADMIN_NAME' => '操作人名称',
+            'PERIOD_NUM' => '所在期数',
+            'CALC_MONTH' => '所在结算月',
+            'P_MONTH' => '表分区的日期索引',
+            'CREATED_AT' => '创建时间',
+            'DELETED' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'SORT' => '排序',
+            'TRANSFER_SN' => '转账流水号',
+            'ORDER_SN' => '订单号',
+        ];
+    }
+}

+ 49 - 0
common/models/OrderPeriodAdjust.php

@@ -0,0 +1,49 @@
+<?php
+
+namespace common\models;
+
+/**
+ * This is the model class for table "{{%ORDER_PERIOD_ADJUST}}".
+ *
+ * @property string $ID
+ * @property string $ORDER_SN 订单号
+ * @property int $ORIGIN_PERIOD 调整前期数
+ * @property int $MODERN_PERIOD 调整后期数
+ * @property string $ADMIN_ID 创建人
+ * @property int $CREATED_AT 创建时间
+ */
+class OrderPeriodAdjust extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%ORDER_PERIOD_ADJUST}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['ORDER_SN', 'ORIGIN_PERIOD', 'MODERN_PERIOD'], 'required'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'ORDER_SN' => '订单号',
+            'ORIGIN_PERIOD' => '调整前期数',
+            'MODERN_PERIOD' => '调整后期数',
+            'ADMIN_ID' => '创建人',
+            'CREATED_AT' => '创建时间',
+        ];
+    }
+}

+ 971 - 956
common/models/Period.php

@@ -1,956 +1,971 @@
-<?php
-
-namespace common\models;
-
-use common\helpers\bonus\Calc\CalcConsole;
-use common\helpers\Date;
-use common\helpers\Tool;
-use Yii;
-use yii\db\Exception;
-
-/**
- * This is the model class for table "{{%PERIOD}}".
- *
- * @property string $ID
- * @property int $PERIOD_NUM 期数
- * @property int $CALC_MONTH 所在结算月
- * @property int $CALC_YEAR 所在结算年
- * @property int $START_TIME 期数开始时间戳
- * @property int $END_TIME 期数结束时间戳
- * @property int $IS_MONTH 是否结算月节点
- * @property int $IS_YEAR 是否结算年节点
- * @property int $IS_CLOSED 是否已封期
- * @property int $IS_PERFED 是否已生成业绩单
- * @property int $IS_CALCULATED 是否已结算
- * @property int $IS_SENT 是否已发放
- * @property int $IS_PERFING 是否正在生成业绩单
- * @property int $IS_CALCING 是否正在计算状态
- * @property int $IS_SENDING 是否正在挂网状态
- * @property int $CALC_PERCENT 结算进度
- * @property int $SENT_PERCENT 发放进度
- * @property string $PERF_ADMIN_ID 生成业绩单管理员
- * @property string $CLOSE_ADMIN_ID 手动封期管理员ID
- * @property string $CALC_ADMIN_ID 结算管理员ID
- * @property string $SENT_ADMIN_ID 发放管理员ID
- * @property int $CLOSED_AT 发放管理员ID
- * @property int $PERF_STARTED_AT 生成业绩单开始时间
- * @property int $PERFED_AT 生成业绩单结束时间
- * @property int $CALCULATE_STARTED_AT 结算开始时间
- * @property int $CALCULATED_AT 结算完成时间
- * @property int $SEND_STARTED_AT 发放开始时间
- * @property int $SENT_AT 发放完成时间
- * @property int $CREATED_AT 创建时间
- */
-class Period extends \common\components\ActiveRecord
-{
-    const CALCULATE_NONE = 0;
-    const CALCULATE_FINISH = 1;
-    const CALCULATE_FAIL = 2;
-
-    const SEND_NONE = 0;
-    const SEND_FINISH = 1;
-    const SEND_FAIL = 2;
-
-    const PERF_NONE = 0;
-    const PERF_FINISH = 1;
-    const PERF_FAIL = 2;
-
-    const SYSTEM_START_PERIOD_NUM = 100;
-
-    const AUTO_EXEC_CALC = 1;
-    const MANUAL_EXEC_CALC = 0;
-    const IS_PROCESSING = 1;
-    const NOT_PROCESSING = 0;
-    const IS_PREPARING = 1;
-    const NOT_PREPARING = 0;
-
-    public $nowPeriodArr = null;
-    public $periodNum = null;
-    public $periodArr = null;
-
-    public function init()
-    {
-        parent::init();
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public static function tableName()
-    {
-        return '{{%PERIOD}}';
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['PERIOD_NUM', 'CALC_MONTH', 'CALC_YEAR', 'START_TIME', 'END_TIME', 'CREATED_AT'], 'required'],
-            [['PERIOD_NUM', 'CALC_MONTH', 'CALC_YEAR', 'START_TIME', 'END_TIME', 'IS_MONTH', 'IS_YEAR', 'IS_CLOSED', 'IS_PERFED', 'IS_CALCULATED', 'IS_SENT', 'IS_PERFING', 'IS_CALCING', 'IS_SENDING', 'CALC_PERCENT', 'SENT_PERCENT', 'CLOSED_AT', 'PERF_STARTED_AT', 'PERFED_AT', 'CALCULATE_STARTED_AT', 'CALCULATED_AT', 'SEND_STARTED_AT', 'SENT_AT', 'CREATED_AT'], 'integer'],
-            [['ID', 'PERF_ADMIN_ID', 'CLOSE_ADMIN_ID', 'CALC_ADMIN_ID', 'SENT_ADMIN_ID'], 'string', 'max' => 32],
-            [['PERIOD_NUM'], 'unique'],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'PERIOD_NUM' => '期数',
-            'CALC_MONTH' => '所在结算月',
-            'CALC_YEAR' => '所在结算年',
-            'START_TIME' => '期数开始时间戳',
-            'END_TIME' => '期数结束时间戳',
-            'IS_MONTH' => '是否结算月节点',
-            'IS_YEAR' => '是否结算年节点',
-            'IS_CLOSED' => '是否已封期',
-            'IS_PERFED' => '是否已生成业绩单',
-            'IS_CALCULATED' => '是否已结算',
-            'IS_SENT' => '是否已发放',
-            'IS_PERFING' => '是否正在生成业绩单',
-            'IS_CALCING' => '是否正在计算状态',
-            'IS_SENDING' => '是否正在挂网状态',
-            'CALC_PERCENT' => '结算进度',
-            'SENT_PERCENT' => '发放进度',
-            'PERF_ADMIN_ID' => '生成业绩单管理员',
-            'CLOSE_ADMIN_ID' => '手动封期管理员ID',
-            'CALC_ADMIN_ID' => '结算管理员ID',
-            'SENT_ADMIN_ID' => '发放管理员ID',
-            'CLOSED_AT' => '发放管理员ID',
-            'PERF_STARTED_AT' => '生成业绩单开始时间',
-            'PERFED_AT' => '生成业绩单结束时间',
-            'CALCULATE_STARTED_AT' => '结算开始时间',
-            'CALCULATED_AT' => '结算完成时间',
-            'SEND_STARTED_AT' => '发放开始时间',
-            'SENT_AT' => '发放完成时间',
-            'CREATED_AT' => '创建时间',
-        ];
-    }
-
-    /**
-     * 期数赋值给属性
-     * @param int $periodNum
-     * @return array|null|\yii\db\ActiveRecord
-     */
-    public function setPeriodNum($periodNum = null){
-        if($periodNum === 0 || $periodNum === null || $periodNum === ''){
-            //if($this->nowPeriodArr === null){
-                $this->nowPeriodArr = static::find()->where('IS_CLOSED=0')->orderBy('PERIOD_NUM ASC')->asArray()->one();
-            //}
-            $this->periodArr = $this->nowPeriodArr;
-            $periodNum = $this->nowPeriodArr['PERIOD_NUM'];
-        } else {
-            if($periodNum !== $this->periodNum){
-                $this->periodArr = static::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
-            }
-        }
-        $this->periodNum = $periodNum;
-        return $this->periodArr;
-    }
-
-    // 通过期数,获取此期数据
-    public static function getInfoByPeriodNum($periodNum) {
-
-        return static::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
-    }
-
-    /**
-     * 是否存在所传期数
-     * @param int $periodNum
-     * @return bool
-     */
-    public static function isExistsPeriodNum(int $periodNum){
-        return static::find()->where(['PERIOD_NUM'=>$periodNum])->exists();
-    }
-
-    /**
-     * 获取当前未封期的最小期数
-     * @return int
-     */
-    public function getNowPeriodNum(){
-        $this->setPeriodNum();
-        if($this->nowPeriodArr){
-            return $this->nowPeriodArr['PERIOD_NUM'];
-        } else {
-            return self::SYSTEM_START_PERIOD_NUM;
-        }
-    }
-
-    /**
-     * 获取当前期的开始时间
-     * @return int
-     */
-    public function getNowPeriodStart(){
-        $this->setPeriodNum();
-        if($this->nowPeriodArr){
-            return $this->nowPeriodArr['START_TIME'];
-        } else {
-            return Date::nowTime();
-        }
-    }
-
-    /**
-     * 获取当前期的结束时间
-     * @return int
-     */
-    public function getNowPeriodEnd(){
-        $this->setPeriodNum();
-        if($this->nowPeriodArr){
-            return $this->nowPeriodArr['END_TIME'];
-        } else {
-            return Date::nowTime();
-        }
-    }
-
-    /**
-     * 获取当前所在的结算月
-     * @return int
-     */
-    public function getNowMonth(){
-        $this->setPeriodNum();
-        if($this->nowPeriodArr){
-            return $this->nowPeriodArr['CALC_MONTH'];
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 获取当前期数所在结算年
-     * @return int
-     */
-    public function getNowYear(){
-        $this->setPeriodNum();
-        if($this->nowPeriodArr){
-            return $this->nowPeriodArr['CALC_YEAR'];
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 当前期数所在年月
-     * @return int|string
-     */
-    public function getNowYearMonth(){
-        $this->setPeriodNum();
-        if($this->nowPeriodArr){
-            return $this->nowPeriodArr['CALC_YEAR'].Tool::numFix($this->nowPeriodArr['CALC_MONTH']);
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 获取期数所在的结算月
-     * @param int $periodNum
-     * @return mixed
-     * @throws Exception
-     */
-    public function getMonth($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            return $period['CALC_MONTH'];
-        } else {
-            throw new Exception('期数不存在');
-        }
-    }
-
-    /**
-     * 获取期数所在的结算年
-     * @param $periodNum
-     * @return mixed
-     * @throws Exception
-     */
-    public function getYear($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            return $period['CALC_YEAR'];
-        } else {
-            throw new Exception('期数不存在');
-        }
-    }
-
-    /**
-     * 期数所在年月
-     * @param $periodNum
-     * @return string
-     * @throws Exception
-     */
-    public function getYearMonth($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            return $period['CALC_YEAR'].Tool::numFix($period['CALC_MONTH'], 2);
-        } else {
-            throw new Exception('期数不存在'.$periodNum);
-        }
-    }
-
-    /**
-     * 所传年、月所有期数的数量
-     * @param $year
-     * @param $month
-     * @return int
-     */
-    public function getYearMonthAllPeriodNumCount($year, $month){
-        return Period::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH', [':CALC_YEAR'=>$year, ':CALC_MONTH'=>$month])->count(1);
-    }
-
-    /**
-     * 是否是结算月节点
-     * @param $periodNum
-     * @return mixed
-     * @throws Exception
-     */
-    public function isCalcMonth($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            return $period['IS_MONTH'];
-        } else {
-            throw new Exception('期数不存在');
-        }
-    }
-
-    /**
-     * 是否是结算年节点
-     * @param $periodNum
-     * @return mixed
-     * @throws Exception
-     */
-    public function isCalcYear($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            return $period['IS_YEAR'];
-        } else {
-            throw new Exception('期数不存在');
-        }
-    }
-
-    /**
-     * 获取挂网的最大期数
-     * @return int
-     */
-    public function getMaxIsSentPeriodNum() {
-        $maxIsSentData = static::find()->where('IS_SENT=1')->orderBy('PERIOD_NUM DESC')->asArray()->one();
-        $maxIsSentPeriodNum = self::SYSTEM_START_PERIOD_NUM;
-        if( $maxIsSentData && $maxIsSentData["PERIOD_NUM"] ) {
-            $maxIsSentPeriodNum = $maxIsSentData["PERIOD_NUM"];
-        }
-
-        return $maxIsSentPeriodNum;
-    }
-
-    /**
-     * 返回所传结算月包含的所有期数
-     * @param $year
-     * @param $month
-     * @return array|\yii\db\ActiveRecord[]
-     */
-    public static function getPeriodNumsFromMonth($year, $month){
-        return static::find()->select('PERIOD_NUM')->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH', [':CALC_YEAR'=>$year, ':CALC_MONTH'=>$month])->orderBy('PERIOD_NUM ASC')->asArray()->all();
-    }
-
-    /**
-     * 获取所传结算月的最小期数和最大期数
-     * @param $year
-     * @param $month
-     * @return array
-     */
-    public static function getPeriodNumRangeFromMonth($year, $month){
-        $allPeriod = self::getPeriodNumsFromMonth($year, $month);
-        $tempPeriod = [];
-        foreach($allPeriod as $period){
-            $tempPeriod[] = $period['PERIOD_NUM'];
-        }
-        if(!$tempPeriod){
-            return null;
-        }
-        $minPeriod = min($tempPeriod);
-        $maxPeriod = max($tempPeriod);
-        return ['min'=>$minPeriod, 'max'=>$maxPeriod];
-    }
-
-    /**
-     * 返回结算月的节点期数
-     * @param $year
-     * @param $month
-     * @return mixed|null
-     */
-    public static function getPeriodNumPointFromMonth($year, $month) {
-        $data = static::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH AND IS_MONTH=1', [':CALC_YEAR'=>$year, ':CALC_MONTH' => $month])->asArray()->one();
-        if($data) return $data['PERIOD_NUM'];
-        else return null;
-    }
-
-    /**
-     * 返回结算月的节点期
-     * @param $year
-     * @param $month
-     * @return mixed|null
-     */
-    public static function getPeriodPointFromMonth($year, $month) {
-        $data = static::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH AND IS_MONTH=1', [':CALC_YEAR'=>$year, ':CALC_MONTH' => $month])->asArray()->one();
-        if($data) return $data;
-        else return null;
-    }
-
-    /**
-     * 是否已经封期
-     * @param $periodNum
-     * @return bool
-     * @throws Exception
-     */
-    public function isClosed($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            return boolval($period['IS_CLOSED']);
-        } else {
-            throw new Exception('期数不存在');
-        }
-    }
-
-    /**
-     * 是否已经生成业绩单
-     * @param $periodNum
-     * @return bool
-     * @throws Exception
-     */
-    public function isPerfed($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            return boolval($period['IS_PERFED']);
-        } else {
-            throw new Exception('期数不存在');
-        }
-    }
-
-    /**
-     * 是否已结算
-     * @param null $periodNum
-     * @return bool
-     * @throws Exception
-     */
-    public function isCalculated($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            return boolval($period['IS_CALCULATED'] == self::CALCULATE_FINISH);
-        } else {
-            throw new Exception('期数不存在');
-        }
-    }
-
-    /**
-     * 是否可被封期
-     * @param $periodNum
-     * @return bool
-     */
-    public function isCanClose($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period['IS_CLOSED']){
-            return false;
-        }
-        $previousPeriod = static::findOne(['PERIOD_NUM'=>$this->periodNum-1]);
-        if($previousPeriod){
-            if(!$previousPeriod['IS_CLOSED']){
-                return false;
-            }
-            // 只要上期封期了,下期就可以封期
-//            if(!$previousPeriod['IS_CALCULATED']){
-//                return false;
-//            }
-//            if(!$previousPeriod['IS_SENT']){
-//                return false;
-//            }
-        }
-        return true;
-    }
-
-    /**
-     * 是否可以生成业绩单
-     * @param $periodNum
-     * @return bool
-     */
-    public function isCanPerf($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        // 查看该期是否已经封期
-        if(!$period['IS_CLOSED']){
-            return false;
-        }
-        // 已经挂网,不能生成业绩单
-        if($period['IS_SENT'] == self::SEND_FINISH){
-            return false;
-        }
-        //上1期奖金未发放,限制不能生成业绩单
-        if(!$this->isLastSent($this->periodNum)){
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * 是否可以结算
-     * @param $periodNum
-     * @return bool
-     */
-    public function isCanCalc($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        // 查看该期是否已经封期
-        if(!$period['IS_CLOSED']){
-            return false;
-        }
-        // 还没有生成业绩单,不能封期
-        if(!$period['IS_PERFED'] || $period['IS_PERFED'] == self::PERF_FAIL){
-            return false;
-        }
-        if($period['IS_SENT'] == self::SEND_FINISH){
-            return false;
-        }
-//        $previousPeriod = static::findOneAsArray(['PERIOD_NUM'=>$this->periodNum-1]);
-//        if($previousPeriod){
-//            // 查看上一期是否已经挂网,上一期挂网了,本期才能结算
-//            if(!$previousPeriod['IS_SENT']){
-//                return false;
-//            }
-//        }
-        //上1期奖金未发放,限制不能结算
-        if(!$this->isLastSent($this->periodNum)){
-            return false;
-        }
-
-        return true;
-    }
-
-    /**
-     * 是否可以挂网
-     * @param $periodNum
-     * @return bool
-     */
-    public function isCanSend($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if(!$period['IS_CLOSED']){
-            return false;
-        }
-        if(!$period['IS_CALCULATED'] || $period['IS_CALCULATED'] == self::CALCULATE_FAIL){
-            return false;
-        }
-        if($period['IS_SENT'] == self::SEND_FINISH){
-            return false;
-        }
-        //上1期奖金未发放,限制不能挂网
-        if(!$this->isLastSent($this->periodNum)){
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * 是否已经挂网
-     * @param $periodNum
-     * @return bool
-     */
-    public function isSent($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period['IS_SENT'] == self::SEND_FINISH) return true;
-        return false;
-    }
-
-    /**
-     * 上期是否挂网
-     * @param null $periodNum
-     * @return bool
-     */
-    public function isLastSent($periodNum){
-        $period = $this->setPeriodNum($periodNum-1);
-        if ($period) {
-            if($period['IS_SENT'] == self::SEND_FINISH) {
-                return true;
-            } else {
-                return false;
-            }
-        }
-
-        return false;
-    }
-
-    /**
-     * 获取上月的年月
-     * @param $periodNum
-     * @return array
-     */
-    public function getLastMonth($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            $year = $period['CALC_YEAR'];
-            $month = $period['CALC_MONTH'];
-            $lastYear = Date::lastMonth($year.'-'.$month, 'Y');
-            $lastMonth = Date::lastMonth($year.'-'.$month, 'm');
-            return [
-                'year' => $lastYear,
-                'month' => intval($lastMonth),
-                'yearMonth' => $lastYear.Tool::numFix($lastMonth, 2),
-            ];
-        } else {
-            return [
-                'year' => 0,
-                'month' => 0,
-                'yearMonth' => 0,
-            ];
-        }
-    }
-
-    /**
-     * 上几个月的年月
-     * @param int $num
-     * @param null $periodNum
-     * @return array
-     */
-    public function getLastNumMonth($num=1,$periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            $year = $period['CALC_YEAR'];
-            $month = $period['CALC_MONTH'];
-            $lastYear = Date::lastNumMonth($num,$year.'-'.$month, 'Y');
-            $lastMonth = Date::lastNumMonth($num,$year.'-'.$month, 'm');
-            return [
-                'year' => $lastYear,
-                'month' => intval($lastMonth),
-                'yearMonth' => $lastYear.Tool::numFix($lastMonth, 2),
-            ];
-        } else {
-            return [
-                'year' => 0,
-                'month' => 0,
-                'yearMonth' => 0,
-            ];
-        }
-    }
-
-    /**
-     * 下月的年月
-     * @param null $periodNum
-     * @return array
-     */
-    public function getNextMonth($periodNum = null){
-        $period = $this->setPeriodNum($periodNum);
-        if($period){
-            $year = $period['CALC_YEAR'];
-            $month = $period['CALC_MONTH'];
-            $nextYear = Date::nextMonth($year.'-'.$month, 'Y');
-            $nextMonth = Date::nextMonth($year.'-'.$month, 'm');
-            return [
-                'year' => $nextYear,
-                'month' => intval($nextMonth),
-                'yearMonth' => $nextYear.Tool::numFix($nextMonth, 2),
-            ];
-        } else {
-            return [
-                'year' => 0,
-                'month' => 0,
-                'yearMonth' => 0,
-            ];
-        }
-    }
-
-    /**
-     * 通过时间戳获取期
-     * @param $time
-     * @return array|null|\yii\db\ActiveRecord
-     */
-    public static function getPeriodFromTime($time){
-        return static::find()->where('START_TIME<=:TIME AND END_TIME>:TIME', [':TIME'=>$time])->asArray()->one();
-    }
-
-    /**
-     * 通过时间戳范围获取期间内的期
-     * @param $minTime
-     * @param $maxTime
-     * @return array|\yii\db\ActiveRecord[]
-     */
-    public static function getPeriodFromTimeRange($minTime, $maxTime){
-        return static::find()->where('END_TIME>:MIN_TIME AND START_TIME<:MAX_TIME', [':MIN_TIME'=>$minTime, ':MAX_TIME'=>$maxTime])->orderBy('PERIOD_NUM ASC')->asArray()->all();
-    }
-
-    /**
-     * 获取近几期的期数
-     * @param $num
-     * @return array
-     */
-    public static function getNearlyPeriodNum($num){
-        // 获取当前期
-        $period = self::instance();
-        $periodNum = $period->getNowPeriodNum();
-        // 获取前$num期的期数
-        $periodNums = [
-            $periodNum
-        ];
-        for($i=0;$i<$num;$i++){
-            if($periodNum - $i > 0){
-                // 查看该期是否存在
-                if(self::isExistsPeriodNum($periodNum - $i)){
-                    $periodNums[] = $periodNum - $i;
-                }
-            }
-        }
-        return array_reverse($periodNums);
-    }
-
-    /**
-     * 获取近几期的挂网期数
-     * @param $num
-     * @return array
-     */
-    public static function getNearlySendPeriodNum($num){
-        // 获取当前期
-        $period = self::instance();
-        $periodNum = $period->sentMaxPeriodNum();
-        // 获取前$num期的期数
-        $periodNums = [
-            $periodNum
-        ];
-        for($i=0;$i<$num;$i++){
-            if($periodNum - $i > 0){
-                // 查看该期是否存在
-                if(self::isExistsPeriodNum($periodNum - $i)){
-                    $periodNums[] = $periodNum - $i;
-                }
-            }
-        }
-        return array_reverse($periodNums);
-    }
-
-    /**
-     * 获取近几期的年月
-     * @param $num
-     * @return array
-     * @throws Exception
-     */
-    public static function getNearlyPeriodYearMonth($num){
-        // 获取当前期
-        $period = self::instance();
-        $periodNum = $period->getNowPeriodNum();
-        $nowYearMonth = $period->getNowYearMonth();
-        // 获取前$num期的期数
-        $periodYearMonths = [];
-        for($i=1;$i<=$num;$i++){
-            if($periodNum - $i > 0){
-                // 查看该期是否存在
-                if(self::isExistsPeriodNum($periodNum - $i)){
-                    $yearMonth = $period->getYearMonth($periodNum - $i);
-                    $periodYearMonths[] = [
-                        'yearMonth' => $yearMonth,
-                        'periodNum' => $periodNum - $i,
-                    ];
-                }
-            }
-        }
-        return array_reverse($periodYearMonths);
-    }
-
-    /**
-     * 获取本月所有已经挂网的期数
-     * @param $yearMonth
-     * @return array
-     */
-    public static function monthSentAllPeriodNum($yearMonth){
-        $year = intval(substr($yearMonth, 0, 4));
-        $month = intval(substr($yearMonth, 4, 2));
-        $allPeriod = Period::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH AND IS_SENT=1', [':CALC_YEAR'=>$year, ':CALC_MONTH'=>$month])->select('PERIOD_NUM')->asArray()->all();
-        $result = [];
-        if($allPeriod){
-            foreach($allPeriod as $period){
-                $result[] = $period['PERIOD_NUM'];
-            }
-        }
-        return $result;
-    }
-
-    /**
-     * 所传月份所有已结算的期数
-     * @param $yearMonth
-     * @return array
-     */
-    public static function monthCalcAllPeriodNum($yearMonth){
-        $year = intval(substr($yearMonth, 0, 4));
-        $month = intval(substr($yearMonth, 4, 2));
-        $allPeriod = Period::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH AND IS_CALCING=1', [':CALC_YEAR'=>$year, ':CALC_MONTH'=>$month])->select('PERIOD_NUM')->asArray()->all();
-        $result = [];
-        if($allPeriod){
-            foreach($allPeriod as $period){
-                $result[] = $period['PERIOD_NUM'];
-            }
-        }
-        return $result;
-    }
-
-    /**
-     * 获取已结算的最大期数
-     * @return mixed
-     */
-    public static function calculatedMaxPeriodNum(){
-        return static::find()->where('IS_CALCULATED=1')->max('PERIOD_NUM');
-    }
-
-    /**
-     * 已挂网的最大期数
-     * @return mixed
-     */
-    public static function sentMaxPeriodNum(){
-        return static::find()->where('IS_SENT=1')->max('PERIOD_NUM');
-    }
-
-    /**
-     * 期数结束时间
-     * @param $periodNum
-     * @return int|mixed
-     */
-    public static function getEndTime($periodNum) {
-        $endTime = static::find()->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $periodNum])->select('END_TIME')->asArray()->one();
-        return $endTime['END_TIME'] ?? 0;
-    }
-
-    /**
-     * 到年底的剩余月份
-     * @param null $periodNum
-     * @return int
-     * @throws Exception
-     */
-    public static function getMonthLeft($periodNum = null) {
-        $period = self::instance();
-        if ($periodNum) {
-            $nowMonth = $period->getMonth($periodNum);
-        } else {
-            $nowMonth = $period->getNowMonth();
-        }
-        return 12 - (int)$nowMonth + 1;
-    }
-
-    /**
-     * 起始期数和结束期数几个月
-     * @param $startPeriodNum
-     * @param $endPeriodNum
-     * @return int|string
-     */
-    public static function getMonthNum($startPeriodNum,$endPeriodNum){
-        return self::find()->select('CALC_MONTH')->groupBy('CALC_MONTH')->where('PERIOD_NUM>=:START_PERIOD AND PERIOD_NUM<=:END_PERIOD',[':START_PERIOD'=>$startPeriodNum,':END_PERIOD'=>$endPeriodNum])->count();
-    }
-
-    /**
-     * 从期数获取当前月的所有期
-     *
-     */
-    public static function getCurrentMonthPeriodByPeriodNum($periodNum){
-        $currentPeriod = self::getInfoByPeriodNum($periodNum);
-        $currentYear = $currentPeriod['CALC_YEAR'];
-        $currentMonth = $currentPeriod['CALC_MONTH'];
-        $periodsArray = self::findAllAsArray(['CALC_YEAR'=>$currentYear,'CALC_MONTH'=>$currentMonth]);
-        $periods = [];
-        foreach ($periodsArray as $p){
-            $periods[] = $p['PERIOD_NUM'];
-        }
-
-        return $periods;
-    }
-
-    public static function getCurrentQuarterPeriodByPeriodNum($periodNum){
-        $currentPeriod = self::getInfoByPeriodNum($periodNum);
-        $currentYear = $currentPeriod['CALC_YEAR'];
-        $currentMonth = $currentPeriod['CALC_MONTH'];
-        $periodsArray = self::find()->select("*")
-            ->where(['CALC_YEAR'=>$currentYear])
-            ->andWhere(['in', 'CALC_MONTH', [$currentMonth-2, $currentMonth-1, $currentMonth]])
-            ->asArray()->all();
-        $periods = [];
-        foreach ($periodsArray as $p){
-            $periods[] = $p['PERIOD_NUM'];
-        }
-
-        return $periods;
-    }
-
-    public static function updatePeriodIsAutoExec($periodNum, $isAutoExec = 0): int
-    {
-        return Period::updateAll(['AUTO_EXEC' => $isAutoExec], ['PERIOD_NUM' => $periodNum]);
-    }
-
-    public static function updatePeriodIsProcessing($periodNum, $isProcessing = 1): int
-    {
-        return Period::updateAll(['IS_PROCESSING' => $isProcessing], ['PERIOD_NUM' => $periodNum]);
-    }
-
-    public static function updatePeriodIsPreparing($periodNum, $isPreparing = 1): int
-    {
-        return Period::updateAll(['IS_PREPARING' => $isPreparing], ['PERIOD_NUM' => $periodNum]);
-    }
-
-    /**
-     * 是否计算操作中
-     * @param $periodNum
-     * @return bool
-     */
-    public static function isProcessing($periodNum = null): bool
-    {
-        $db        = CalcConsole::CALC_DB_NAME;
-        $allPeriod = \Yii::$app->$db->createCommand("SELECT * FROM AR_PERIOD order by PERIOD_NUM desc")->queryAll();
-        $calcPeriod    = [];
-        foreach ($allPeriod as $v) {
-            if ($v['IS_PREPARE'] > 0) {
-                $calcPeriod = $v;
-                break;
-            }
-        }
-        $period = static::findOneAsArray(['PERIOD_NUM' => $periodNum]);
-        // 若计算服务中CALC_ID不为空,则不允许计算
-        if ($calcPeriod) {
-            if ($calcPeriod['CALC_ID']) return true;
-        }
-        //挂网则拒绝操作,返回true则拒绝操作
-        if ($period['IS_SENT'] == self::SEND_FINISH) return true;
-        if ($period['IS_PROCESSING'] == self::IS_PROCESSING) return true;
-        return false;
-    }
-
-    /**
-     * 是否预计算操作中
-     * @param $periodNum
-     * @return bool
-     */
-    public static function isPreparing($periodNum = null): bool
-    {
-        $period = static::findOneAsArray(['PERIOD_NUM' => $periodNum]);
-        //挂网则拒绝操作,返回true则拒绝操作
-        if ($period['IS_SENT'] == self::SEND_FINISH) return true;
-        if ($period['IS_PREPARING'] == self::IS_PREPARING) return true;
-        $nowTs = time();
-        if ($nowTs-6 > $period['END_TIME']) return true;
-        return false;
-    }
-
-    public static function checkPerf($periodNum){
-        $result = static::find()
-            ->where(
-                'PERIOD_NUM=:PERIOD_NUM ', [':PERIOD_NUM' => $periodNum]
-            )
-            ->asArray()
-            ->one();
-
-        if (isset($result['IS_PERFED']) && $result['IS_PERFED'] == 1) {
-            return true;
-        }
-
-        return false;
-    }
-
-    public static function checkClose($periodNum){
-        $period = static::findOneAsArray(['PERIOD_NUM' => $periodNum]);
-        if ($period['IS_CLOSED'] == 1) {
-            return true;
-        }
-        return false;
-    }
-}
+<?php
+
+namespace common\models;
+
+use common\helpers\bonus\Calc\CalcConsole;
+use common\helpers\Date;
+use common\helpers\Tool;
+use Yii;
+use yii\db\Exception;
+
+/**
+ * This is the model class for table "{{%PERIOD}}".
+ *
+ * @property string $ID
+ * @property int $PERIOD_NUM 期数
+ * @property int $CALC_MONTH 所在结算月
+ * @property int $CALC_YEAR 所在结算年
+ * @property int $START_TIME 期数开始时间戳
+ * @property int $END_TIME 期数结束时间戳
+ * @property int $IS_MONTH 是否结算月节点
+ * @property int $IS_YEAR 是否结算年节点
+ * @property int $IS_CLOSED 是否已封期
+ * @property int $IS_PERFED 是否已生成业绩单
+ * @property int $IS_CALCULATED 是否已结算
+ * @property int $IS_SENT 是否已发放
+ * @property int $IS_PERFING 是否正在生成业绩单
+ * @property int $IS_CALCING 是否正在计算状态
+ * @property int $IS_SENDING 是否正在挂网状态
+ * @property int $CALC_PERCENT 结算进度
+ * @property int $SENT_PERCENT 发放进度
+ * @property string $PERF_ADMIN_ID 生成业绩单管理员
+ * @property string $CLOSE_ADMIN_ID 手动封期管理员ID
+ * @property string $CALC_ADMIN_ID 结算管理员ID
+ * @property string $SENT_ADMIN_ID 发放管理员ID
+ * @property int $CLOSED_AT 发放管理员ID
+ * @property int $PERF_STARTED_AT 生成业绩单开始时间
+ * @property int $PERFED_AT 生成业绩单结束时间
+ * @property int $CALCULATE_STARTED_AT 结算开始时间
+ * @property int $CALCULATED_AT 结算完成时间
+ * @property int $SEND_STARTED_AT 发放开始时间
+ * @property int $SENT_AT 发放完成时间
+ * @property int $CREATED_AT 创建时间
+ */
+class Period extends \common\components\ActiveRecord
+{
+    const CALCULATE_NONE = 0;
+    const CALCULATE_FINISH = 1;
+    const CALCULATE_FAIL = 2;
+
+    const SEND_NONE = 0;
+    const SEND_FINISH = 1;
+    const SEND_FAIL = 2;
+
+    const PERF_NONE = 0;
+    const PERF_FINISH = 1;
+    const PERF_FAIL = 2;
+
+    const SYSTEM_START_PERIOD_NUM = 100;
+
+    const AUTO_EXEC_CALC = 1;
+    const MANUAL_EXEC_CALC = 0;
+    const IS_PROCESSING = 1;
+    const NOT_PROCESSING = 0;
+    const IS_PREPARING = 1;
+    const NOT_PREPARING = 0;
+
+    public $nowPeriodArr = null;
+    public $periodNum = null;
+    public $periodArr = null;
+
+    public function init()
+    {
+        parent::init();
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public static function tableName()
+    {
+        return '{{%PERIOD}}';
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['PERIOD_NUM', 'CALC_MONTH', 'CALC_YEAR', 'START_TIME', 'END_TIME', 'CREATED_AT'], 'required'],
+            [['PERIOD_NUM', 'CALC_MONTH', 'CALC_YEAR', 'START_TIME', 'END_TIME', 'IS_MONTH', 'IS_YEAR', 'IS_CLOSED', 'IS_PERFED', 'IS_CALCULATED', 'IS_SENT', 'IS_PERFING', 'IS_CALCING', 'IS_SENDING', 'CALC_PERCENT', 'SENT_PERCENT', 'CLOSED_AT', 'PERF_STARTED_AT', 'PERFED_AT', 'CALCULATE_STARTED_AT', 'CALCULATED_AT', 'SEND_STARTED_AT', 'SENT_AT', 'CREATED_AT'], 'integer'],
+            [['ID', 'PERF_ADMIN_ID', 'CLOSE_ADMIN_ID', 'CALC_ADMIN_ID', 'SENT_ADMIN_ID'], 'string', 'max' => 32],
+            [['PERIOD_NUM'], 'unique'],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'PERIOD_NUM' => '期数',
+            'CALC_MONTH' => '所在结算月',
+            'CALC_YEAR' => '所在结算年',
+            'START_TIME' => '期数开始时间戳',
+            'END_TIME' => '期数结束时间戳',
+            'IS_MONTH' => '是否结算月节点',
+            'IS_YEAR' => '是否结算年节点',
+            'IS_CLOSED' => '是否已封期',
+            'IS_PERFED' => '是否已生成业绩单',
+            'IS_CALCULATED' => '是否已结算',
+            'IS_SENT' => '是否已发放',
+            'IS_PERFING' => '是否正在生成业绩单',
+            'IS_CALCING' => '是否正在计算状态',
+            'IS_SENDING' => '是否正在挂网状态',
+            'CALC_PERCENT' => '结算进度',
+            'SENT_PERCENT' => '发放进度',
+            'PERF_ADMIN_ID' => '生成业绩单管理员',
+            'CLOSE_ADMIN_ID' => '手动封期管理员ID',
+            'CALC_ADMIN_ID' => '结算管理员ID',
+            'SENT_ADMIN_ID' => '发放管理员ID',
+            'CLOSED_AT' => '发放管理员ID',
+            'PERF_STARTED_AT' => '生成业绩单开始时间',
+            'PERFED_AT' => '生成业绩单结束时间',
+            'CALCULATE_STARTED_AT' => '结算开始时间',
+            'CALCULATED_AT' => '结算完成时间',
+            'SEND_STARTED_AT' => '发放开始时间',
+            'SENT_AT' => '发放完成时间',
+            'CREATED_AT' => '创建时间',
+        ];
+    }
+
+    /**
+     * 期数赋值给属性
+     * @param int $periodNum
+     * @return array|null|\yii\db\ActiveRecord
+     */
+    public function setPeriodNum($periodNum = null){
+        if($periodNum === 0 || $periodNum === null || $periodNum === ''){
+            //if($this->nowPeriodArr === null){
+                $this->nowPeriodArr = static::find()->where('IS_CLOSED=0')->orderBy('PERIOD_NUM ASC')->asArray()->one();
+            //}
+            $this->periodArr = $this->nowPeriodArr;
+            $periodNum = $this->nowPeriodArr['PERIOD_NUM'];
+        } else {
+            if($periodNum !== $this->periodNum){
+                $this->periodArr = static::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
+            }
+        }
+        $this->periodNum = $periodNum;
+        return $this->periodArr;
+    }
+
+    // 通过期数,获取此期数据
+    public static function getInfoByPeriodNum($periodNum) {
+
+        return static::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
+    }
+
+    /**
+     * 是否存在所传期数
+     * @param int $periodNum
+     * @return bool
+     */
+    public static function isExistsPeriodNum(int $periodNum){
+        return static::find()->where(['PERIOD_NUM'=>$periodNum])->exists();
+    }
+
+    /**
+     * 获取当前未封期的最小期数
+     * @return int
+     */
+    public function getNowPeriodNum(){
+        $this->setPeriodNum();
+        if($this->nowPeriodArr){
+            return $this->nowPeriodArr['PERIOD_NUM'];
+        } else {
+            return self::SYSTEM_START_PERIOD_NUM;
+        }
+    }
+
+    /**
+     * 获取当前期的开始时间
+     * @return int
+     */
+    public function getNowPeriodStart(){
+        $this->setPeriodNum();
+        if($this->nowPeriodArr){
+            return $this->nowPeriodArr['START_TIME'];
+        } else {
+            return Date::nowTime();
+        }
+    }
+
+    /**
+     * 获取当前期的结束时间
+     * @return int
+     */
+    public function getNowPeriodEnd(){
+        $this->setPeriodNum();
+        if($this->nowPeriodArr){
+            return $this->nowPeriodArr['END_TIME'];
+        } else {
+            return Date::nowTime();
+        }
+    }
+
+    /**
+     * 获取当前所在的结算月
+     * @return int
+     */
+    public function getNowMonth(){
+        $this->setPeriodNum();
+        if($this->nowPeriodArr){
+            return $this->nowPeriodArr['CALC_MONTH'];
+        } else {
+            return 0;
+        }
+    }
+
+    /**
+     * 获取当前期数所在结算年
+     * @return int
+     */
+    public function getNowYear(){
+        $this->setPeriodNum();
+        if($this->nowPeriodArr){
+            return $this->nowPeriodArr['CALC_YEAR'];
+        } else {
+            return 0;
+        }
+    }
+
+    /**
+     * 当前期数所在年月
+     * @return int|string
+     */
+    public function getNowYearMonth(){
+        $this->setPeriodNum();
+        if($this->nowPeriodArr){
+            return $this->nowPeriodArr['CALC_YEAR'].Tool::numFix($this->nowPeriodArr['CALC_MONTH']);
+        } else {
+            return 0;
+        }
+    }
+
+    /**
+     * 获取期数所在的结算月
+     * @param int $periodNum
+     * @return mixed
+     * @throws Exception
+     */
+    public function getMonth($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            return $period['CALC_MONTH'];
+        } else {
+            throw new Exception('期数不存在');
+        }
+    }
+
+    /**
+     * 获取期数所在的结算年
+     * @param $periodNum
+     * @return mixed
+     * @throws Exception
+     */
+    public function getYear($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            return $period['CALC_YEAR'];
+        } else {
+            throw new Exception('期数不存在');
+        }
+    }
+
+    /**
+     * 期数所在年月
+     * @param $periodNum
+     * @return string
+     * @throws Exception
+     */
+    public function getYearMonth($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            return $period['CALC_YEAR'].Tool::numFix($period['CALC_MONTH'], 2);
+        } else {
+            throw new Exception('期数不存在'.$periodNum);
+        }
+    }
+
+    /**
+     * 所传年、月所有期数的数量
+     * @param $year
+     * @param $month
+     * @return int
+     */
+    public function getYearMonthAllPeriodNumCount($year, $month){
+        return Period::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH', [':CALC_YEAR'=>$year, ':CALC_MONTH'=>$month])->count(1);
+    }
+
+    /**
+     * 是否是结算月节点
+     * @param $periodNum
+     * @return mixed
+     * @throws Exception
+     */
+    public function isCalcMonth($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            return $period['IS_MONTH'];
+        } else {
+            throw new Exception('期数不存在');
+        }
+    }
+
+    /**
+     * 是否是结算年节点
+     * @param $periodNum
+     * @return mixed
+     * @throws Exception
+     */
+    public function isCalcYear($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            return $period['IS_YEAR'];
+        } else {
+            throw new Exception('期数不存在');
+        }
+    }
+
+    /**
+     * 获取挂网的最大期数
+     * @return int
+     */
+    public function getMaxIsSentPeriodNum() {
+        $maxIsSentData = static::find()->where('IS_SENT=1')->orderBy('PERIOD_NUM DESC')->asArray()->one();
+        $maxIsSentPeriodNum = self::SYSTEM_START_PERIOD_NUM;
+        if( $maxIsSentData && $maxIsSentData["PERIOD_NUM"] ) {
+            $maxIsSentPeriodNum = $maxIsSentData["PERIOD_NUM"];
+        }
+
+        return $maxIsSentPeriodNum;
+    }
+
+    /**
+     * 返回所传结算月包含的所有期数
+     * @param $year
+     * @param $month
+     * @return array|\yii\db\ActiveRecord[]
+     */
+    public static function getPeriodNumsFromMonth($year, $month){
+        return static::find()->select('PERIOD_NUM')->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH', [':CALC_YEAR'=>$year, ':CALC_MONTH'=>$month])->orderBy('PERIOD_NUM ASC')->asArray()->all();
+    }
+
+    /**
+     * 获取所传结算月的最小期数和最大期数
+     * @param $year
+     * @param $month
+     * @return array
+     */
+    public static function getPeriodNumRangeFromMonth($year, $month){
+        $allPeriod = self::getPeriodNumsFromMonth($year, $month);
+        $tempPeriod = [];
+        foreach($allPeriod as $period){
+            $tempPeriod[] = $period['PERIOD_NUM'];
+        }
+        if(!$tempPeriod){
+            return null;
+        }
+        $minPeriod = min($tempPeriod);
+        $maxPeriod = max($tempPeriod);
+        return ['min'=>$minPeriod, 'max'=>$maxPeriod];
+    }
+
+    /**
+     * 返回结算月的节点期数
+     * @param $year
+     * @param $month
+     * @return mixed|null
+     */
+    public static function getPeriodNumPointFromMonth($year, $month) {
+        $data = static::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH AND IS_MONTH=1', [':CALC_YEAR'=>$year, ':CALC_MONTH' => $month])->asArray()->one();
+        if($data) return $data['PERIOD_NUM'];
+        else return null;
+    }
+
+    /**
+     * 返回结算月的节点期
+     * @param $year
+     * @param $month
+     * @return mixed|null
+     */
+    public static function getPeriodPointFromMonth($year, $month) {
+        $data = static::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH AND IS_MONTH=1', [':CALC_YEAR'=>$year, ':CALC_MONTH' => $month])->asArray()->one();
+        if($data) return $data;
+        else return null;
+    }
+
+    /**
+     * 是否已经封期
+     * @param $periodNum
+     * @return bool
+     * @throws Exception
+     */
+    public function isClosed($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            return boolval($period['IS_CLOSED']);
+        } else {
+            throw new Exception('期数不存在');
+        }
+    }
+
+    /**
+     * 是否已经生成业绩单
+     * @param $periodNum
+     * @return bool
+     * @throws Exception
+     */
+    public function isPerfed($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            return boolval($period['IS_PERFED']);
+        } else {
+            throw new Exception('期数不存在');
+        }
+    }
+
+    /**
+     * 是否已结算
+     * @param null $periodNum
+     * @return bool
+     * @throws Exception
+     */
+    public function isCalculated($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            return boolval($period['IS_CALCULATED'] == self::CALCULATE_FINISH);
+        } else {
+            throw new Exception('期数不存在');
+        }
+    }
+
+    /**
+     * 是否可被封期
+     * @param $periodNum
+     * @return bool
+     */
+    public function isCanClose($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period['IS_CLOSED']){
+            return false;
+        }
+        $previousPeriod = static::findOne(['PERIOD_NUM'=>$this->periodNum-1]);
+        if($previousPeriod){
+            if(!$previousPeriod['IS_CLOSED']){
+                return false;
+            }
+            // 只要上期封期了,下期就可以封期
+//            if(!$previousPeriod['IS_CALCULATED']){
+//                return false;
+//            }
+//            if(!$previousPeriod['IS_SENT']){
+//                return false;
+//            }
+        }
+        return true;
+    }
+
+    /**
+     * 是否可以生成业绩单
+     * @param $periodNum
+     * @return bool
+     */
+    public function isCanPerf($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        // 查看该期是否已经封期
+        if(!$period['IS_CLOSED']){
+            return false;
+        }
+        // 已经挂网,不能生成业绩单
+        if($period['IS_SENT'] == self::SEND_FINISH){
+            return false;
+        }
+        //上1期奖金未发放,限制不能生成业绩单
+        if(!$this->isLastSent($this->periodNum)){
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * 是否可以结算
+     * @param $periodNum
+     * @return bool
+     */
+    public function isCanCalc($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        // 查看该期是否已经封期
+        if(!$period['IS_CLOSED']){
+            return false;
+        }
+        // 还没有生成业绩单,不能封期
+        if(!$period['IS_PERFED'] || $period['IS_PERFED'] == self::PERF_FAIL){
+            return false;
+        }
+        if($period['IS_SENT'] == self::SEND_FINISH){
+            return false;
+        }
+//        $previousPeriod = static::findOneAsArray(['PERIOD_NUM'=>$this->periodNum-1]);
+//        if($previousPeriod){
+//            // 查看上一期是否已经挂网,上一期挂网了,本期才能结算
+//            if(!$previousPeriod['IS_SENT']){
+//                return false;
+//            }
+//        }
+        //上1期奖金未发放,限制不能结算
+        if(!$this->isLastSent($this->periodNum)){
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * 是否可以挂网
+     * @param $periodNum
+     * @return bool
+     */
+    public function isCanSend($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if(!$period['IS_CLOSED']){
+            return false;
+        }
+        if(!$period['IS_CALCULATED'] || $period['IS_CALCULATED'] == self::CALCULATE_FAIL){
+            return false;
+        }
+        if($period['IS_SENT'] == self::SEND_FINISH){
+            return false;
+        }
+        //上1期奖金未发放,限制不能挂网
+        if(!$this->isLastSent($this->periodNum)){
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * 是否已经挂网
+     * @param $periodNum
+     * @return bool
+     */
+    public function isSent($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period['IS_SENT'] == self::SEND_FINISH) return true;
+        return false;
+    }
+
+    /**
+     * 上期是否挂网
+     * @param null $periodNum
+     * @return bool
+     */
+    public function isLastSent($periodNum){
+        $period = $this->setPeriodNum($periodNum-1);
+        if ($period) {
+            if($period['IS_SENT'] == self::SEND_FINISH) {
+                return true;
+            } else {
+                return false;
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * 获取上月的年月
+     * @param $periodNum
+     * @return array
+     */
+    public function getLastMonth($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            $year = $period['CALC_YEAR'];
+            $month = $period['CALC_MONTH'];
+            $lastYear = Date::lastMonth($year.'-'.$month, 'Y');
+            $lastMonth = Date::lastMonth($year.'-'.$month, 'm');
+            return [
+                'year' => $lastYear,
+                'month' => intval($lastMonth),
+                'yearMonth' => $lastYear.Tool::numFix($lastMonth, 2),
+            ];
+        } else {
+            return [
+                'year' => 0,
+                'month' => 0,
+                'yearMonth' => 0,
+            ];
+        }
+    }
+
+    /**
+     * 上几个月的年月
+     * @param int $num
+     * @param null $periodNum
+     * @return array
+     */
+    public function getLastNumMonth($num=1,$periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            $year = $period['CALC_YEAR'];
+            $month = $period['CALC_MONTH'];
+            $lastYear = Date::lastNumMonth($num,$year.'-'.$month, 'Y');
+            $lastMonth = Date::lastNumMonth($num,$year.'-'.$month, 'm');
+            return [
+                'year' => $lastYear,
+                'month' => intval($lastMonth),
+                'yearMonth' => $lastYear.Tool::numFix($lastMonth, 2),
+            ];
+        } else {
+            return [
+                'year' => 0,
+                'month' => 0,
+                'yearMonth' => 0,
+            ];
+        }
+    }
+
+    /**
+     * 下月的年月
+     * @param null $periodNum
+     * @return array
+     */
+    public function getNextMonth($periodNum = null){
+        $period = $this->setPeriodNum($periodNum);
+        if($period){
+            $year = $period['CALC_YEAR'];
+            $month = $period['CALC_MONTH'];
+            $nextYear = Date::nextMonth($year.'-'.$month, 'Y');
+            $nextMonth = Date::nextMonth($year.'-'.$month, 'm');
+            return [
+                'year' => $nextYear,
+                'month' => intval($nextMonth),
+                'yearMonth' => $nextYear.Tool::numFix($nextMonth, 2),
+            ];
+        } else {
+            return [
+                'year' => 0,
+                'month' => 0,
+                'yearMonth' => 0,
+            ];
+        }
+    }
+
+    /**
+     * 通过时间戳获取期
+     * @param $time
+     * @return array|null|\yii\db\ActiveRecord
+     */
+    public static function getPeriodFromTime($time){
+        return static::find()->where('START_TIME<=:TIME AND END_TIME>:TIME', [':TIME'=>$time])->asArray()->one();
+    }
+
+    /**
+     * 通过时间戳范围获取期间内的期
+     * @param $minTime
+     * @param $maxTime
+     * @return array|\yii\db\ActiveRecord[]
+     */
+    public static function getPeriodFromTimeRange($minTime, $maxTime){
+        return static::find()->where('END_TIME>:MIN_TIME AND START_TIME<:MAX_TIME', [':MIN_TIME'=>$minTime, ':MAX_TIME'=>$maxTime])->orderBy('PERIOD_NUM ASC')->asArray()->all();
+    }
+
+    /**
+     * 获取近几期的期数
+     * @param $num
+     * @return array
+     */
+    public static function getNearlyPeriodNum($num){
+        // 获取当前期
+        $period = self::instance();
+        $periodNum = $period->getNowPeriodNum();
+        // 获取前$num期的期数
+        $periodNums = [
+            $periodNum
+        ];
+        for($i=0;$i<$num;$i++){
+            if($periodNum - $i > 0){
+                // 查看该期是否存在
+                if(self::isExistsPeriodNum($periodNum - $i)){
+                    $periodNums[] = $periodNum - $i;
+                }
+            }
+        }
+        return array_reverse($periodNums);
+    }
+
+    /**
+     * 获取近几期的挂网期数
+     * @param $num
+     * @return array
+     */
+    public static function getNearlySendPeriodNum($num){
+        // 获取当前期
+        $period = self::instance();
+        $periodNum = $period->sentMaxPeriodNum();
+        // 获取前$num期的期数
+        $periodNums = [
+            $periodNum
+        ];
+        for($i=0;$i<$num;$i++){
+            if($periodNum - $i > 0){
+                // 查看该期是否存在
+                if(self::isExistsPeriodNum($periodNum - $i)){
+                    $periodNums[] = $periodNum - $i;
+                }
+            }
+        }
+        return array_reverse($periodNums);
+    }
+
+    /**
+     * 获取近几期的年月
+     * @param $num
+     * @return array
+     * @throws Exception
+     */
+    public static function getNearlyPeriodYearMonth($num){
+        // 获取当前期
+        $period = self::instance();
+        $periodNum = $period->getNowPeriodNum();
+        $nowYearMonth = $period->getNowYearMonth();
+        // 获取前$num期的期数
+        $periodYearMonths = [];
+        for($i=1;$i<=$num;$i++){
+            if($periodNum - $i > 0){
+                // 查看该期是否存在
+                if(self::isExistsPeriodNum($periodNum - $i)){
+                    $yearMonth = $period->getYearMonth($periodNum - $i);
+                    $periodYearMonths[] = [
+                        'yearMonth' => $yearMonth,
+                        'periodNum' => $periodNum - $i,
+                    ];
+                }
+            }
+        }
+        return array_reverse($periodYearMonths);
+    }
+
+    /**
+     * 获取本月所有已经挂网的期数
+     * @param $yearMonth
+     * @return array
+     */
+    public static function monthSentAllPeriodNum($yearMonth){
+        $year = intval(substr($yearMonth, 0, 4));
+        $month = intval(substr($yearMonth, 4, 2));
+        $allPeriod = Period::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH AND IS_SENT=1', [':CALC_YEAR'=>$year, ':CALC_MONTH'=>$month])->select('PERIOD_NUM')->asArray()->all();
+        $result = [];
+        if($allPeriod){
+            foreach($allPeriod as $period){
+                $result[] = $period['PERIOD_NUM'];
+            }
+        }
+        return $result;
+    }
+
+    /**
+     * 所传月份所有已结算的期数
+     * @param $yearMonth
+     * @return array
+     */
+    public static function monthCalcAllPeriodNum($yearMonth){
+        $year = intval(substr($yearMonth, 0, 4));
+        $month = intval(substr($yearMonth, 4, 2));
+        $allPeriod = Period::find()->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH AND IS_CALCING=1', [':CALC_YEAR'=>$year, ':CALC_MONTH'=>$month])->select('PERIOD_NUM')->asArray()->all();
+        $result = [];
+        if($allPeriod){
+            foreach($allPeriod as $period){
+                $result[] = $period['PERIOD_NUM'];
+            }
+        }
+        return $result;
+    }
+
+    /**
+     * 获取已结算的最大期数
+     * @return mixed
+     */
+    public static function calculatedMaxPeriodNum(){
+        return static::find()->where('IS_CALCULATED=1')->max('PERIOD_NUM');
+    }
+
+    /**
+     * 已挂网的最大期数
+     * @return mixed
+     */
+    public static function sentMaxPeriodNum(){
+        return static::find()->where('IS_SENT=1')->max('PERIOD_NUM');
+    }
+
+    /**
+     * 期数结束时间
+     * @param $periodNum
+     * @return int|mixed
+     */
+    public static function getEndTime($periodNum) {
+        $endTime = static::find()->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $periodNum])->select('END_TIME')->asArray()->one();
+        return $endTime['END_TIME'] ?? 0;
+    }
+
+    /**
+     * 到年底的剩余月份
+     * @param null $periodNum
+     * @return int
+     * @throws Exception
+     */
+    public static function getMonthLeft($periodNum = null) {
+        $period = self::instance();
+        if ($periodNum) {
+            $nowMonth = $period->getMonth($periodNum);
+        } else {
+            $nowMonth = $period->getNowMonth();
+        }
+        return 12 - (int)$nowMonth + 1;
+    }
+
+    /**
+     * 起始期数和结束期数几个月
+     * @param $startPeriodNum
+     * @param $endPeriodNum
+     * @return int|string
+     */
+    public static function getMonthNum($startPeriodNum,$endPeriodNum){
+        return self::find()->select('CALC_MONTH')->groupBy('CALC_MONTH')->where('PERIOD_NUM>=:START_PERIOD AND PERIOD_NUM<=:END_PERIOD',[':START_PERIOD'=>$startPeriodNum,':END_PERIOD'=>$endPeriodNum])->count();
+    }
+
+    /**
+     * 从期数获取当前月的所有期
+     *
+     */
+    public static function getCurrentMonthPeriodByPeriodNum($periodNum){
+        $currentPeriod = self::getInfoByPeriodNum($periodNum);
+        $currentYear = $currentPeriod['CALC_YEAR'];
+        $currentMonth = $currentPeriod['CALC_MONTH'];
+        $periodsArray = self::findAllAsArray(['CALC_YEAR'=>$currentYear,'CALC_MONTH'=>$currentMonth]);
+        $periods = [];
+        foreach ($periodsArray as $p){
+            $periods[] = $p['PERIOD_NUM'];
+        }
+
+        return $periods;
+    }
+
+    public static function getCurrentQuarterPeriodByPeriodNum($periodNum){
+        $currentPeriod = self::getInfoByPeriodNum($periodNum);
+        $currentYear = $currentPeriod['CALC_YEAR'];
+        $currentMonth = $currentPeriod['CALC_MONTH'];
+        $periodsArray = self::find()->select("*")
+            ->where(['CALC_YEAR'=>$currentYear])
+            ->andWhere(['in', 'CALC_MONTH', [$currentMonth-2, $currentMonth-1, $currentMonth]])
+            ->asArray()->all();
+        $periods = [];
+        foreach ($periodsArray as $p){
+            $periods[] = $p['PERIOD_NUM'];
+        }
+
+        return $periods;
+    }
+
+    public static function updatePeriodIsAutoExec($periodNum, $isAutoExec = 0): int
+    {
+        return Period::updateAll(['AUTO_EXEC' => $isAutoExec], ['PERIOD_NUM' => $periodNum]);
+    }
+
+    public static function updatePeriodIsProcessing($periodNum, $isProcessing = 1): int
+    {
+        return Period::updateAll(['IS_PROCESSING' => $isProcessing], ['PERIOD_NUM' => $periodNum]);
+    }
+
+    public static function updatePeriodIsPreparing($periodNum, $isPreparing = 1): int
+    {
+        return Period::updateAll(['IS_PREPARING' => $isPreparing], ['PERIOD_NUM' => $periodNum]);
+    }
+
+    /**
+     * 是否计算操作中
+     * @param $periodNum
+     * @return bool
+     */
+    public static function isProcessing($periodNum = null): bool
+    {
+        $db        = CalcConsole::CALC_DB_NAME;
+        $allPeriod = \Yii::$app->$db->createCommand("SELECT * FROM AR_PERIOD order by PERIOD_NUM desc")->queryAll();
+        $calcPeriod    = [];
+        foreach ($allPeriod as $v) {
+            if ($v['IS_PREPARE'] > 0) {
+                $calcPeriod = $v;
+                break;
+            }
+        }
+        $period = static::findOneAsArray(['PERIOD_NUM' => $periodNum]);
+        // 若计算服务中CALC_ID不为空,则不允许计算
+        if ($calcPeriod) {
+            if ($calcPeriod['CALC_ID']) return true;
+        }
+        //挂网则拒绝操作,返回true则拒绝操作
+        if ($period['IS_SENT'] == self::SEND_FINISH) return true;
+        if ($period['IS_PROCESSING'] == self::IS_PROCESSING) return true;
+        return false;
+    }
+
+    /**
+     * 是否预计算操作中
+     * @param $periodNum
+     * @return bool
+     */
+    public static function isPreparing($periodNum = null): bool
+    {
+        $period = static::findOneAsArray(['PERIOD_NUM' => $periodNum]);
+        //挂网则拒绝操作,返回true则拒绝操作
+        if ($period['IS_SENT'] == self::SEND_FINISH) return true;
+        if ($period['IS_PREPARING'] == self::IS_PREPARING) return true;
+        $nowTs = time();
+        if ($nowTs-6 > $period['END_TIME']) return true;
+        return false;
+    }
+
+    public static function checkPerf($periodNum){
+        $result = static::find()
+            ->where(
+                'PERIOD_NUM=:PERIOD_NUM ', [':PERIOD_NUM' => $periodNum]
+            )
+            ->asArray()
+            ->one();
+
+        if (isset($result['IS_PERFED']) && $result['IS_PERFED'] == 1) {
+            return true;
+        }
+
+        return false;
+    }
+
+    public static function checkClose($periodNum){
+        $period = static::findOneAsArray(['PERIOD_NUM' => $periodNum]);
+        if ($period['IS_CLOSED'] == 1) {
+            return true;
+        }
+        return false;
+    }
+    
+   /**
+     * 获取期数列表
+     * @param null $periodNum
+     * @param int $limit
+     * @return array|\yii\db\ActiveRecord[]
+     */
+    public static function getPeriodList($periodNum = null, $limit = 10) {
+        if ($periodNum) {
+            $periodList = static::find()->where('PERIOD_NUM >= :PERIOD_NUM', [':PERIOD_NUM' => $periodNum])->select('PERIOD_NUM,IS_SENT,IS_CLOSED')->limit($limit)->asArray()->all();
+        } else {
+            $periodList = static::find()->select('PERIOD_NUM,IS_SENT,IS_CLOSED')->limit($limit)->column();
+        }
+        return $periodList;
+    }
+}

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

@@ -934,12 +934,12 @@ class DeclarationForm extends Model
                 throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
             }
             //扣报单人现金钱包
-//            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'报单']);
-            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'To'.$this->insertUserName.'Entry']);
+//            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'报单', 'ORDER_SN' => $orderModel->SN]);
+            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'To'.$this->insertUserName.'Entry', 'ORDER_SN' => $orderModel->SN]);
             return $addressModel;
         }else{
             $addressModel = new ReceiveAddress();
-            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'To'.$this->insertUserName.'Entry']);
+            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'To'.$this->insertUserName.'Entry', 'ORDER_SN' => $orderModel->SN]);
             return $addressModel;
         }
     }
@@ -964,8 +964,8 @@ class DeclarationForm extends Model
             }
             // 如果是复销单的话,还需要考虑给会员的复销池减去金额
             elseif($this->type == self::TYPE_FX){
-//                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
-                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'Deletion deduction', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
+//                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV, 'ORDER_SN' => $orderModel->SN]);
+                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'Deletion deduction', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV, 'ORDER_SN' => $oneOrder['SN']]);
             }
             $transaction->commit();
         } catch (Exception $e) {

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

@@ -388,8 +388,8 @@ class DeclarationUpgradeForm extends Model
                 throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
             }
             // 扣报单人现金钱包
-//            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'升级报单']);
-            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'by'.$this->insertUserName.'Upgrade entry']);
+//            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'升级报单', 'ORDER_SN' => $orderModel->SN]);
+            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'by'.$this->insertUserName.'Upgrade entry', 'ORDER_SN' => $orderModel->SN]);
             // 为被升级人进行升级操作
             $decLevelLog = new DecLevelLog();
             $decLog = [

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

@@ -148,7 +148,7 @@ class OrderDeleteForm extends Model
                     );
                 }
 
-                $userId = $decInfo['USER_ID']; 
+                $userId = $decInfo['USER_ID'];
 
                 if (!$delDecOrder) {
                     $transaction->rollBack();
@@ -223,11 +223,11 @@ class OrderDeleteForm extends Model
                 $payAmount = $orderInfo['PAY_AMOUNT']; // 支付的金额
                 //退还
                 if ($payType == 'cash') {
-                    $amountResult = Cash::changeUserCash($userId, 'CASH', +abs($payAmount), ['REMARK' => '退货退还余额']);
+                    $amountResult = Cash::changeUserCash($userId, 'CASH', +abs($payAmount), ['REMARK' => '退货退还余额', 'ORDER_SN' => $orderInfo['SN']]);
                 } else if ($payType == 'exchange') {
-                    $amountResult = Balance::changeUserBonus($userId, 'exchange_points', +abs($payAmount), ['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE, 'REMARK' => '退货退还无业绩兑换点数']);
+                    $amountResult = Balance::changeUserBonus($userId, 'exchange_points', +abs($payAmount), ['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE, 'REMARK' => '退货退还无业绩兑换点数', 'ORDER_SN' => $orderInfo['SN']]);
                 } else {
-                    $amountResult = Balance::changeUserBonus($userId, 'reconsume_points', +abs($payAmount), ['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '退货退还复销点数']);
+                    $amountResult = Balance::changeUserBonus($userId, 'reconsume_points', +abs($payAmount), ['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '退货退还复销点数', 'ORDER_SN' => $orderInfo['SN']]);
                 }
 
                 if ($amountResult !== true) {
@@ -332,7 +332,7 @@ class OrderDeleteForm extends Model
                     return false;
                 }
             }
-            
+
             $transaction->commit();
         } catch(Exception $e) {
             $transaction->rollBack();
@@ -482,8 +482,8 @@ class OrderDeleteForm extends Model
                     $this->addError($attribute, \Yii::t('ctx', 'shopRegisterHasFxOrder').$this->orderSn);
                     return ;
                 }
-            }   
+            }
         }
-        return true; 
+        return true;
     }
 }

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

@@ -765,17 +765,17 @@ class OrderForm extends Model
 
         //扣除会员余额/积分
         if($this->payType=='cash') {
-            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => 'Members reselling balance payment']); // 会员复销余额支付
+            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => 'Members reselling balance payment', 'ORDER_SN' => $orderModel->SN]); // 会员复销余额支付
         } else if ($this->payType=='exchange') {
-            Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换']);
+            Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换', 'ORDER_SN' => $orderModel->SN]);
         } else if ($this->payType == 'tourism_points') {
-            Balance::changeUserBonus(\Yii::$app->user->id, 'tourism_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TOURISM_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换']);
+            Balance::changeUserBonus(\Yii::$app->user->id, 'tourism_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TOURISM_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换', 'ORDER_SN' => $orderModel->SN]);
         } else if ($this->payType == 'garage_points') {
-            Balance::changeUserBonus(\Yii::$app->user->id, 'garage_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::GARAGE_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换']);
+            Balance::changeUserBonus(\Yii::$app->user->id, 'garage_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::GARAGE_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换', 'ORDER_SN' => $orderModel->SN]);
         }  else if ($this->payType == 'villa_points') {
-            Balance::changeUserBonus(\Yii::$app->user->id, 'villa_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::VILLA_POINTS_EXCHANGE,'REMARK' => '会员房奖积分兑换']);
+            Balance::changeUserBonus(\Yii::$app->user->id, 'villa_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::VILLA_POINTS_EXCHANGE,'REMARK' => '会员房奖积分兑换', 'ORDER_SN' => $orderModel->SN]);
         } else if ($this->payType == 'reconsume_points') {
-            Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换']);
+            Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换', 'ORDER_SN' => $orderModel->SN]);
         }
 
 //        if($this->_remainPv>0) {

+ 165 - 0
common/models/forms/OrderPeriodAdjustForm.php

@@ -0,0 +1,165 @@
+<?php
+namespace common\models\forms;
+
+use backendApi\modules\v1\models\Admin;
+use common\helpers\Date;
+use common\components\Model;
+use common\helpers\LoggerTool;
+use common\libs\logging\operate\AdminOperate;
+use common\models\DecOrder;
+use common\models\FlowExchangePoints;
+use common\models\FlowGaragePoints;
+use common\models\FlowReconsumePoints;
+use common\models\FlowTourismPoints;
+use common\models\FlowVillaPoints;
+use common\models\FlowWallet;
+use common\models\Order;
+use common\models\OrderPeriodAdjust;
+use common\models\Period;
+use common\models\User;
+use common\models\UserInfo;
+
+/**
+ * OrderPeriodAdjustForm form
+ */
+class OrderPeriodAdjustForm extends Model
+{
+    public $orderSn;
+    public $modernPeriod;
+
+    public $order;
+
+    public function init() {
+        parent::init();
+        $this->adminOperateLogger = new AdminOperate([
+            'fetchClass' => OrderPeriodAdjust::class,
+        ]);
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['orderSn', 'modernPeriod'], 'trim'],
+            [['orderSn', 'modernPeriod'], 'required'],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'orderSn' => '订单号',
+            'modernPeriod' => '调整后期数',
+        ];
+    }
+
+    /**
+     * 指定校验场景
+     * @return array
+     */
+    public function scenarios()
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            'orderPeriodAdjust' => ['orderSn', 'modernPeriod'],
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * 校验之前
+     * @return bool
+     */
+    public function beforeValidate()
+    {
+        $parentValidate = parent::beforeValidate();
+        // 校验订单
+        $this->order = Order::findOne(['SN' => $this->orderSn, 'IS_DELETE' => 0]);
+        if (!$this->order) {
+            $this->addError('orderSn', '订单不存在');
+            return false;
+        }
+        // 目前期数:已封期、未挂网可调整
+        $period = Period::getInfoByPeriodNum($this->modernPeriod);
+        if (!$period) {
+            $this->addError('modernPeriod', '期数不存在');
+            return false;
+        }
+        if (!((+$period['IS_CLOSED'] == 1) && (+$period['IS_SENT'] == 0))) {
+            $this->addError('orderSn', '调整后的期数必须是已封期且未挂网');
+            return false;
+        }
+
+        return $parentValidate;
+    }
+
+    /**
+     * @return bool|null
+     */
+    public function periodAdjust()
+    {
+        if (!$this->validate()) {
+            return null;
+        }
+
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            // 调整订单期数
+            Order::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'SN = :SN', [':SN' => $this->orderSn]);
+
+            if ($this->order->ORDER_TYPE === 'ZC') {
+                // 调整报单期数
+                DecOrder::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
+                // 调整会员的期数
+                User::updateAll(['PERIOD_AT' => $this->modernPeriod], 'ID = :USER_ID', ['USER_ID' => $this->order->USER_ID]);
+                UserInfo::updateAll(['HIGHEST_EMP_LV_PERIOD' => $this->modernPeriod], 'USER_ID = :USER_ID', ['USER_ID' => $this->order->USER_ID]);
+            }
+
+            // 调整流水的期数
+            switch ($this->order->PAY_TYPE){
+                case 'cash':
+                    FlowWallet::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
+                    break;
+                case 'exchange':
+                    FlowExchangePoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
+                    break;
+                case 'tourism_points':
+                    FlowTourismPoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
+                    break;
+                case 'garage_points':
+                    FlowGaragePoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
+                    break;
+                case 'villa_points':
+                    FlowVillaPoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
+                    break;
+                case 'reconsume_points':
+                    FlowReconsumePoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
+                    break;
+                default:
+                    break;
+            }
+
+            // 写入调整记录
+            $orderModel = new OrderPeriodAdjust();
+            $orderModel->ORDER_SN = $this->orderSn;
+            $orderModel->DEC_SN = $this->order->DEC_SN ?? '';
+            $orderModel->ORIGIN_PERIOD = $this->order->PERIOD_NUM;
+            $orderModel->MODERN_PERIOD = $this->modernPeriod;
+            $orderModel->ADMIN_ID = Admin::getAdminNameById(\Yii::$app->user->id);
+            $orderModel->CREATED_AT = Date::nowTime();
+            if (!$orderModel->save()) {
+                $this->addErrors($orderModel->getErrors());
+                return false;
+            }
+            $transaction->commit();
+        } catch(\Exception $e) {
+            $transaction->rollBack();
+            $this->addError('periodAdjust', $e->getMessage());
+            return null;
+        }
+        return true;
+    }
+}