Browse Source

流水相关表,增加记录订单号字段

theo 2 years ago
parent
commit
6189feaac3

+ 7 - 3
backendApi/modules/v1/models/lists/bonus/FlowBalanceList.php

@@ -26,9 +26,9 @@ class FlowBalanceList extends \common\libs\dataList\DataList implements DataList
      * @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,
+            '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',
@@ -189,6 +189,10 @@ class FlowBalanceList extends \common\libs\dataList\DataList implements DataList
                     'header' => '流水号',
                     'headerOther' => ['width' => '250'],
                 ],
+                'ORDER_SN' => [
+                    'header' => '订单号',
+                    'headerOther' => ['width' => '250'],
+                ],
             ];
         }
         return $this->columns;
@@ -223,4 +227,4 @@ class FlowBalanceList extends \common\libs\dataList\DataList implements DataList
         }
         return $this->filterTypes;
     }
-}
+}

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

@@ -1,252 +1,252 @@
-<?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\FlowBonus;
-use common\libs\dataList\column\DateTime;
-use Yii;
-
-class FlowBonusList extends \common\libs\dataList\DataList implements DataListInterface {
-    /**
-     * 列表名称
-     * @return string
-     */
-    public function getListName() {
-        return '奖金流水';
-    }
-
-    /**
-     * 列表筛选到的数据
-     * @throws \yii\base\Exception
-     */
-    public function dataHandle() {
-        $this->listData = FlowBonus::lists($this->condition, $this->params, [
-            'select' => 'FB.*,U.USER_NAME,U.REAL_NAME,U.IS_DEC',
-            'orderBy' => 'FB.CREATED_AT DESC,FB.SORT DESC,FB.AUTO_SORT DESC,FB.ID DESC',
-            'from' => FlowBonus::tableName() . ' AS FB',
-            'join' => [
-                ['LEFT JOIN', \common\models\User::tableName() . ' AS U', 'FB.USER_ID=U.ID'],
-            ],
-            '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']
-                    ],
-                ],
-//                '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']
-                        ];
-                    },
-                ],
-//                'DEC_ROLE_NAME' => [
-//                    'header' => '报单中心级别',
-//                    'headerOther' => ['width' => '110'],
-//                ],
-//                'IS_DIRECT_SELLER' => [
-//                    'header' => '是否直销员',
-//                    'value' => function ($row) {
-//                        return (new YesNo([
-//                            'value' => $row['IS_DIRECT_SELLER'],
-//                        ]))->result();
-//                    },
-//                    'headerOther' => function ($row) {
-//                        return [
-//                            'width' => '120',
-//                        ];
-//                    },
-//                    'valueOther' => function ($row) {
-//                        return [
-//                            'tag' => ['type' => (isset($row['IS_DIRECT_SELLER']) && $row['IS_DIRECT_SELLER']) ? '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\FlowBonus;
+use common\libs\dataList\column\DateTime;
+use Yii;
+
+class FlowBonusList extends \common\libs\dataList\DataList implements DataListInterface {
+    /**
+     * 列表名称
+     * @return string
+     */
+    public function getListName() {
+        return '奖金流水';
+    }
+
+    /**
+     * 列表筛选到的数据
+     * @throws \yii\base\Exception
+     */
+    public function dataHandle() {
+        $this->listData = FlowBonus::lists($this->condition, $this->params, [
+            'select' => 'FB.*,U.USER_NAME,U.REAL_NAME,U.IS_DEC',
+            'orderBy' => 'FB.CREATED_AT DESC,FB.SORT DESC,FB.AUTO_SORT DESC,FB.ID DESC',
+            'from' => FlowBonus::tableName() . ' AS FB',
+            'join' => [
+                ['LEFT JOIN', \common\models\User::tableName() . ' AS U', 'FB.USER_ID=U.ID'],
+            ],
+            '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']
+                    ],
+                ],
+//                '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']
+                        ];
+                    },
+                ],
+//                'DEC_ROLE_NAME' => [
+//                    'header' => '报单中心级别',
+//                    'headerOther' => ['width' => '110'],
+//                ],
+//                'IS_DIRECT_SELLER' => [
+//                    'header' => '是否直销员',
+//                    'value' => function ($row) {
+//                        return (new YesNo([
+//                            'value' => $row['IS_DIRECT_SELLER'],
+//                        ]))->result();
+//                    },
+//                    'headerOther' => function ($row) {
+//                        return [
+//                            'width' => '120',
+//                        ];
+//                    },
+//                    'valueOther' => function ($row) {
+//                        return [
+//                            'tag' => ['type' => (isset($row['IS_DIRECT_SELLER']) && $row['IS_DIRECT_SELLER']) ? '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;
+    }
+}

+ 5 - 1
backendApi/modules/v1/models/lists/bonus/FlowExchangePointsList.php

@@ -175,6 +175,10 @@ class FlowExchangePointsList extends \common\libs\dataList\DataList implements D
                     'header' => '备注',
                     'headerOther' => ['width' => '250'],
                 ],
+                'ORDER_SN' => [
+                    'header' => '订单号',
+                    'headerOther' => ['width' => '250'],
+                ],
             ];
         }
         return $this->columns;
@@ -204,4 +208,4 @@ class FlowExchangePointsList extends \common\libs\dataList\DataList implements D
         }
         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;
+    }
+}

+ 854 - 853
common/helpers/user/Balance.php

@@ -1,853 +1,854 @@
-<?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\FlowLX;
-use common\models\FlowReconsumePoints;
-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';
-
-    /**
-     * 发票流水
-     * @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
-     * @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);
-        // 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;
-            default:
-                throw new Exception('流水类型错误');
-        }
-        if (RedisLock::instance()->lock($lockKey)) {
-            // 改变发奖
-            $paramData = [];
-            $oneUserBonusModel = UserBonus::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('金额不足');
-                }
-
-                if (isset($params['QY'])) {
-                    $paramData['QY_TOTAL'] = new Expression('QY_TOTAL + '.$params['QY']);
-                    //$oneUserBonusModel->QY_TOTAL += $params['QY'];
-                }
-                if (isset($params['FW'])) {
-                    $paramData['FW_TOTAL'] = new Expression('FW_TOTAL + '.$params['FW']);
-                }
-                if (isset($params['YC'])) {
-                    $paramData['YC_TOTAL'] = new Expression('YC_TOTAL + '.$params['YC']);
-                    //$oneUserBonusModel->YC_TOTAL += $params['YC'];
-                }
-                if (isset($params['VIP'])) {
-                    $paramData['VIP_TOTAL'] = new Expression('VIP_TOTAL + '.$params['VIP']);
-                }
-                if (isset($params['BD'])) {
-                    $paramData['BD_TOTAL'] = new Expression('BD_TOTAL + '.$params['BD']);
-                    //$oneUserBonusModel->BD_TOTAL += $params['BD'];
-                }
-                if (isset($params['TG'])) {
-                    $paramData['TG_TOTAL'] = new Expression('TG_TOTAL + '.$params['TG']);
-                    //$oneUserBonusModel->TG_TOTAL += $params['TG'];
-                }
-                if (isset($params['YJ'])) {
-                    $paramData['YJ_TOTAL'] = new Expression('YJ_TOTAL + '.$params['YJ']);
-                    //$oneUserBonusModel->YJ_TOTAL += $params['YJ'];
-                }
-                if (isset($params['GX'])) {
-                    $paramData['GX_TOTAL'] = new Expression('GX_TOTAL + '.$params['GX']);
-                    //$oneUserBonusModel->GX_TOTAL += $params['GX'];
-                }
-                if (isset($params['GL'])) {
-                    $paramData['GL_TOTAL'] = new Expression('GL_TOTAL + '.$params['GL']);
-                    //$oneUserBonusModel->GL_TOTAL += $params['GL'];
-                }
-                if (isset($params['BS'])) {
-                    $paramData['BS_TOTAL'] = new Expression('BS_TOTAL + '.$params['BS']);
-                    //$oneUserBonusModel->GL_TOTAL += $params['GL'];
-                }
-                if (isset($params['ST'])) {
-                    $paramData['STORE_TOTAL'] = new Expression('STORE_TOTAL + '.$params['ST']);
-                }
-                if (isset($params['RECONSUME_POINTS_TOTAL'])) {
-                    $paramData['RECONSUME_POINTS_TOTAL'] = new Expression('RECONSUME_POINTS_TOTAL + '.$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 + '.$params['EXCHANGE_POINTS_TOTAL']);
-                    //$oneUserBonusModel->RECONSUME_POINTS_TOTAL += $params['RECONSUME_POINTS_TOTAL'];
-                }
-                if (isset($params['MANAGE_TAX'])) {
-                    $paramData['MANAGE_TAX'] = new Expression('MANAGE_TAX + '.$params['MANAGE_TAX']);
-                    //$oneUserBonusModel->MANAGE_TAX += $params['MANAGE_TAX'];
-                }
-
-                if (isset($params['ORI_QY'])) {
-                    $paramData['ORI_QY_TOTAL'] = new Expression('ORI_QY_TOTAL + '.$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 + '.$params['ORI_YC']);
-                    //$oneUserBonusModel->ORI_YC_TOTAL += $params['ORI_YC'];
-                }
-                if (isset($params['ORI_VIP'])) {
-                    $paramData['ORI_VIP_TOTAL'] = new Expression('ORI_VIP_TOTAL + '.$params['ORI_VIP']);
-                }
-                if (isset($params['ORI_VIP'])) {
-                    $paramData['ORI_VIP_TOTAL'] = new Expression('ORI_VIP_TOTAL + '.$params['ORI_VIP']);
-                }
-                if (isset($params['ORI_STANDARD'])) {
-                    $paramData['ORI_STANDARD_TOTAL'] = new Expression('ORI_STANDARD_TOTAL + '.$params['ORI_STANDARD']);
-                }
-                if (isset($params['ORI_TG'])) {
-                    $paramData['ORI_TG_TOTAL'] = new Expression('ORI_TG_TOTAL + '.$params['ORI_TG']);
-                    //$oneUserBonusModel->ORI_TG_TOTAL += $params['ORI_TG'];
-                }
-                if (isset($params['ORI_YJ'])) {
-                    $paramData['ORI_YJ_TOTAL'] = new Expression('ORI_YJ_TOTAL + '.$params['ORI_YJ']);
-                    //$oneUserBonusModel->ORI_YJ_TOTAL += $params['ORI_YJ'];
-                }
-                if (isset($params['ORI_GX'])) {
-                    $paramData['ORI_GX_TOTAL'] = new Expression('ORI_GX_TOTAL + '.$params['ORI_GX']);
-                    //$oneUserBonusModel->ORI_GX_TOTAL += $params['ORI_GX'];
-                }
-                if (isset($params['ORI_GL'])) {
-                    $paramData['ORI_GL_TOTAL'] = new Expression('ORI_GL_TOTAL + '.$params['ORI_GL']);
-                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
-                }
-                if (isset($params['ORI_BS'])) {
-                    $paramData['ORI_BS_TOTAL'] = new Expression('ORI_BS_TOTAL + '.$params['ORI_BS']);
-                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
-                }
-                if (isset($params['ORI_ST'])) {
-                    $paramData['ORI_STORE_TOTAL'] = new Expression('ORI_STORE_TOTAL + '.$params['ORI_ST']);
-                }
-
-                if (isset($params['BONUS_TOTAL'])) {
-                    $paramData['BONUS_TOTAL'] = new Expression('BONUS_TOTAL + '.$params['BONUS_TOTAL']);
-                    //$oneUserBonusModel->BONUS_TOTAL += $params['BONUS_TOTAL'];
-                }
-                UserBonus::updateAll($paramData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-
-            } else {
-                $paramData = [
-                    'USER_ID'=>$userId,
-                    $type=>$amount,
-                    'CREATED_AT'=>Date::nowTime()
-                ];
-                if (isset($params['QY'])) {
-//                    $paramData['QY_TOTAL'] = new Expression('QY_TOTAL + '.$params['QY']);
-                    $paramData['QY_TOTAL'] = $params['QY'];
-                }
-                if (isset($params['FW'])) {
-//                    $paramData['FW_TOTAL'] = new Expression('FW_TOTAL + '.$params['FW']);
-                    $paramData['FW_TOTAL'] = $params['FW'];
-                }
-                if (isset($params['YC'])) {
-//                    $paramData['YC_TOTAL'] = new Expression('YC_TOTAL + '.$params['YC']);
-                    $paramData['YC_TOTAL'] = $params['YC'];
-                }
-                if (isset($params['VIP'])) {
-//                    $paramData['VIP_TOTAL'] = new Expression('VIP_TOTAL + '.$params['VIP']);
-                    $paramData['VIP_TOTAL'] = $params['VIP'];
-                }
-
-                if (isset($params['BD'])) {
-//                    $paramData['BD_TOTAL'] = new Expression('BD_TOTAL + '.$params['BD']);
-                    $paramData['BD_TOTAL'] = $params['BD'];
-                    //$oneUserBonusModel->BD_TOTAL += $params['BD'];
-                }
-                if (isset($params['TG'])) {
-//                    $paramData['TG_TOTAL'] = new Expression('TG_TOTAL + '.$params['TG']);
-                    $paramData['TG_TOTAL'] = $params['TG'];
-                }
-                if (isset($params['YJ'])) {
-//                    $paramData['YJ_TOTAL'] = new Expression('YJ_TOTAL + '.$params['YJ']);
-                    $paramData['YJ_TOTAL'] = $params['YJ'];
-                }
-                if (isset($params['GX'])) {
-//                    $paramData['GX_TOTAL'] = new Expression('GX_TOTAL + '.$params['GX']);
-                    $paramData['GX_TOTAL'] = $params['GX'];
-                }
-                if (isset($params['GL'])) {
-//                    $paramData['GL_TOTAL'] = new Expression('GL_TOTAL + '.$params['GL']);
-                    $paramData['GL_TOTAL'] = $params['GL'];
-                }
-                if (isset($params['BS'])) {
-                    $paramData['BS_TOTAL'] = $params['BS'];
-                    //$oneUserBonusModel->GL_TOTAL += $params['GL'];
-                }
-                if (isset($params['RECONSUME_POINTS_TOTAL'])) {
-//                    $paramData['RECONSUME_POINTS_TOTAL'] = new Expression('RECONSUME_POINTS_TOTAL + '.$params['RECONSUME_POINTS_TOTAL']);
-                    $paramData['RECONSUME_POINTS_TOTAL'] = $params['RECONSUME_POINTS_TOTAL'];
-                }
-                if (isset($params['MANAGE_TAX'])) {
-//                    $paramData['MANAGE_TAX'] = new Expression('MANAGE_TAX + '.$params['MANAGE_TAX']);
-                    $paramData['MANAGE_TAX'] = $params['MANAGE_TAX'];
-                }
-
-                if (isset($params['ORI_QY'])) {
-//                    $paramData['ORI_QY_TOTAL'] = new Expression('ORI_QY_TOTAL + '.$params['ORI_QY']);
-                    $paramData['ORI_QY_TOTAL'] = $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'] = $params['ORI_YC'];
-                }
-                if (isset($params['ORI_VIP'])) {
-//                    $paramData['ORI_VIP_TOTAL'] = new Expression('ORI_VIP_TOTAL + '.$params['ORI_VIP']);
-                    $paramData['ORI_VIP_TOTAL'] = $params['ORI_VIP'];
-                }
-                if (isset($params['ORI_STANDARD'])) {
-                    $paramData['ORI_STANDARD_TOTAL'] = $params['ORI_STANDARD'];
-                }
-                if (isset($params['ORI_BD'])) {
-//                    $paramData['ORI_BD_TOTAL'] = new Expression('ORI_BD_TOTAL + '.$params['ORI_BD']);
-                    $paramData['ORI_BD_TOTAL'] = $params['ORI_BD'];
-                }
-                if (isset($params['ORI_TG'])) {
-//                    $paramData['ORI_TG_TOTAL'] = new Expression('ORI_TG_TOTAL + '.$params['ORI_TG']);
-                    $paramData['ORI_TG_TOTAL'] = $params['ORI_TG'];
-                }
-                if (isset($params['ORI_YJ'])) {
-//                    $paramData['ORI_YJ_TOTAL'] = new Expression('ORI_YJ_TOTAL + '.$params['ORI_YJ']);
-                    $paramData['ORI_YJ_TOTAL'] = $params['ORI_YJ'];
-                }
-                if (isset($params['ORI_GX'])) {
-//                    $paramData['ORI_GX_TOTAL'] = new Expression('ORI_GX_TOTAL + '.$params['ORI_GX']);
-                    $paramData['ORI_GX_TOTAL'] = $params['ORI_GX'];
-                }
-                if (isset($params['ORI_GL'])) {
-//                    $paramData['ORI_GL_TOTAL'] = new Expression('ORI_GL_TOTAL + '.$params['ORI_GL']);
-                    $paramData['ORI_GL_TOTAL'] = $params['ORI_GL'];
-                }
-                if (isset($params['ORI_BS'])) {
-                    $paramData['ORI_BS_TOTAL'] = $params['ORI_BS'];
-                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
-                }
-
-                if (isset($params['BONUS_TOTAL'])) {
-//                    $paramData['BONUS_TOTAL'] = new Expression('BONUS_TOTAL + '.$params['BONUS_TOTAL']);
-                    $paramData['BONUS_TOTAL'] = $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' => $amount,
-                '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,
-            ];
-            unset($userInfo, $oneUserBonus);
-            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, $amount);
-                }else {
-                    self::deductPeriodExchangePoints($userId, abs($amount));
-                }
-                FlowExchangePoints::insertOne($flowInsertData);
-            } elseif (strtolower($type) == 'cf') {
-                FlowCF::insertOne($flowInsertData);
-            } elseif (strtolower($type) == 'lx') {
-                FlowLX::insertOne($flowInsertData);
-            }
-            unset($flowInsertData);
-            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\FlowLX;
+use common\models\FlowReconsumePoints;
+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';
+
+    /**
+     * 发票流水
+     * @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
+     * @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);
+        // 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;
+            default:
+                throw new Exception('流水类型错误');
+        }
+        if (RedisLock::instance()->lock($lockKey)) {
+            // 改变发奖
+            $paramData = [];
+            $oneUserBonusModel = UserBonus::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('金额不足');
+                }
+
+                if (isset($params['QY'])) {
+                    $paramData['QY_TOTAL'] = new Expression('QY_TOTAL + '.$params['QY']);
+                    //$oneUserBonusModel->QY_TOTAL += $params['QY'];
+                }
+                if (isset($params['FW'])) {
+                    $paramData['FW_TOTAL'] = new Expression('FW_TOTAL + '.$params['FW']);
+                }
+                if (isset($params['YC'])) {
+                    $paramData['YC_TOTAL'] = new Expression('YC_TOTAL + '.$params['YC']);
+                    //$oneUserBonusModel->YC_TOTAL += $params['YC'];
+                }
+                if (isset($params['VIP'])) {
+                    $paramData['VIP_TOTAL'] = new Expression('VIP_TOTAL + '.$params['VIP']);
+                }
+                if (isset($params['BD'])) {
+                    $paramData['BD_TOTAL'] = new Expression('BD_TOTAL + '.$params['BD']);
+                    //$oneUserBonusModel->BD_TOTAL += $params['BD'];
+                }
+                if (isset($params['TG'])) {
+                    $paramData['TG_TOTAL'] = new Expression('TG_TOTAL + '.$params['TG']);
+                    //$oneUserBonusModel->TG_TOTAL += $params['TG'];
+                }
+                if (isset($params['YJ'])) {
+                    $paramData['YJ_TOTAL'] = new Expression('YJ_TOTAL + '.$params['YJ']);
+                    //$oneUserBonusModel->YJ_TOTAL += $params['YJ'];
+                }
+                if (isset($params['GX'])) {
+                    $paramData['GX_TOTAL'] = new Expression('GX_TOTAL + '.$params['GX']);
+                    //$oneUserBonusModel->GX_TOTAL += $params['GX'];
+                }
+                if (isset($params['GL'])) {
+                    $paramData['GL_TOTAL'] = new Expression('GL_TOTAL + '.$params['GL']);
+                    //$oneUserBonusModel->GL_TOTAL += $params['GL'];
+                }
+                if (isset($params['BS'])) {
+                    $paramData['BS_TOTAL'] = new Expression('BS_TOTAL + '.$params['BS']);
+                    //$oneUserBonusModel->GL_TOTAL += $params['GL'];
+                }
+                if (isset($params['ST'])) {
+                    $paramData['STORE_TOTAL'] = new Expression('STORE_TOTAL + '.$params['ST']);
+                }
+                if (isset($params['RECONSUME_POINTS_TOTAL'])) {
+                    $paramData['RECONSUME_POINTS_TOTAL'] = new Expression('RECONSUME_POINTS_TOTAL + '.$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 + '.$params['EXCHANGE_POINTS_TOTAL']);
+                    //$oneUserBonusModel->RECONSUME_POINTS_TOTAL += $params['RECONSUME_POINTS_TOTAL'];
+                }
+                if (isset($params['MANAGE_TAX'])) {
+                    $paramData['MANAGE_TAX'] = new Expression('MANAGE_TAX + '.$params['MANAGE_TAX']);
+                    //$oneUserBonusModel->MANAGE_TAX += $params['MANAGE_TAX'];
+                }
+
+                if (isset($params['ORI_QY'])) {
+                    $paramData['ORI_QY_TOTAL'] = new Expression('ORI_QY_TOTAL + '.$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 + '.$params['ORI_YC']);
+                    //$oneUserBonusModel->ORI_YC_TOTAL += $params['ORI_YC'];
+                }
+                if (isset($params['ORI_VIP'])) {
+                    $paramData['ORI_VIP_TOTAL'] = new Expression('ORI_VIP_TOTAL + '.$params['ORI_VIP']);
+                }
+                if (isset($params['ORI_VIP'])) {
+                    $paramData['ORI_VIP_TOTAL'] = new Expression('ORI_VIP_TOTAL + '.$params['ORI_VIP']);
+                }
+                if (isset($params['ORI_STANDARD'])) {
+                    $paramData['ORI_STANDARD_TOTAL'] = new Expression('ORI_STANDARD_TOTAL + '.$params['ORI_STANDARD']);
+                }
+                if (isset($params['ORI_TG'])) {
+                    $paramData['ORI_TG_TOTAL'] = new Expression('ORI_TG_TOTAL + '.$params['ORI_TG']);
+                    //$oneUserBonusModel->ORI_TG_TOTAL += $params['ORI_TG'];
+                }
+                if (isset($params['ORI_YJ'])) {
+                    $paramData['ORI_YJ_TOTAL'] = new Expression('ORI_YJ_TOTAL + '.$params['ORI_YJ']);
+                    //$oneUserBonusModel->ORI_YJ_TOTAL += $params['ORI_YJ'];
+                }
+                if (isset($params['ORI_GX'])) {
+                    $paramData['ORI_GX_TOTAL'] = new Expression('ORI_GX_TOTAL + '.$params['ORI_GX']);
+                    //$oneUserBonusModel->ORI_GX_TOTAL += $params['ORI_GX'];
+                }
+                if (isset($params['ORI_GL'])) {
+                    $paramData['ORI_GL_TOTAL'] = new Expression('ORI_GL_TOTAL + '.$params['ORI_GL']);
+                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
+                }
+                if (isset($params['ORI_BS'])) {
+                    $paramData['ORI_BS_TOTAL'] = new Expression('ORI_BS_TOTAL + '.$params['ORI_BS']);
+                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
+                }
+                if (isset($params['ORI_ST'])) {
+                    $paramData['ORI_STORE_TOTAL'] = new Expression('ORI_STORE_TOTAL + '.$params['ORI_ST']);
+                }
+
+                if (isset($params['BONUS_TOTAL'])) {
+                    $paramData['BONUS_TOTAL'] = new Expression('BONUS_TOTAL + '.$params['BONUS_TOTAL']);
+                    //$oneUserBonusModel->BONUS_TOTAL += $params['BONUS_TOTAL'];
+                }
+                UserBonus::updateAll($paramData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
+
+            } else {
+                $paramData = [
+                    'USER_ID'=>$userId,
+                    $type=>$amount,
+                    'CREATED_AT'=>Date::nowTime()
+                ];
+                if (isset($params['QY'])) {
+//                    $paramData['QY_TOTAL'] = new Expression('QY_TOTAL + '.$params['QY']);
+                    $paramData['QY_TOTAL'] = $params['QY'];
+                }
+                if (isset($params['FW'])) {
+//                    $paramData['FW_TOTAL'] = new Expression('FW_TOTAL + '.$params['FW']);
+                    $paramData['FW_TOTAL'] = $params['FW'];
+                }
+                if (isset($params['YC'])) {
+//                    $paramData['YC_TOTAL'] = new Expression('YC_TOTAL + '.$params['YC']);
+                    $paramData['YC_TOTAL'] = $params['YC'];
+                }
+                if (isset($params['VIP'])) {
+//                    $paramData['VIP_TOTAL'] = new Expression('VIP_TOTAL + '.$params['VIP']);
+                    $paramData['VIP_TOTAL'] = $params['VIP'];
+                }
+
+                if (isset($params['BD'])) {
+//                    $paramData['BD_TOTAL'] = new Expression('BD_TOTAL + '.$params['BD']);
+                    $paramData['BD_TOTAL'] = $params['BD'];
+                    //$oneUserBonusModel->BD_TOTAL += $params['BD'];
+                }
+                if (isset($params['TG'])) {
+//                    $paramData['TG_TOTAL'] = new Expression('TG_TOTAL + '.$params['TG']);
+                    $paramData['TG_TOTAL'] = $params['TG'];
+                }
+                if (isset($params['YJ'])) {
+//                    $paramData['YJ_TOTAL'] = new Expression('YJ_TOTAL + '.$params['YJ']);
+                    $paramData['YJ_TOTAL'] = $params['YJ'];
+                }
+                if (isset($params['GX'])) {
+//                    $paramData['GX_TOTAL'] = new Expression('GX_TOTAL + '.$params['GX']);
+                    $paramData['GX_TOTAL'] = $params['GX'];
+                }
+                if (isset($params['GL'])) {
+//                    $paramData['GL_TOTAL'] = new Expression('GL_TOTAL + '.$params['GL']);
+                    $paramData['GL_TOTAL'] = $params['GL'];
+                }
+                if (isset($params['BS'])) {
+                    $paramData['BS_TOTAL'] = $params['BS'];
+                    //$oneUserBonusModel->GL_TOTAL += $params['GL'];
+                }
+                if (isset($params['RECONSUME_POINTS_TOTAL'])) {
+//                    $paramData['RECONSUME_POINTS_TOTAL'] = new Expression('RECONSUME_POINTS_TOTAL + '.$params['RECONSUME_POINTS_TOTAL']);
+                    $paramData['RECONSUME_POINTS_TOTAL'] = $params['RECONSUME_POINTS_TOTAL'];
+                }
+                if (isset($params['MANAGE_TAX'])) {
+//                    $paramData['MANAGE_TAX'] = new Expression('MANAGE_TAX + '.$params['MANAGE_TAX']);
+                    $paramData['MANAGE_TAX'] = $params['MANAGE_TAX'];
+                }
+
+                if (isset($params['ORI_QY'])) {
+//                    $paramData['ORI_QY_TOTAL'] = new Expression('ORI_QY_TOTAL + '.$params['ORI_QY']);
+                    $paramData['ORI_QY_TOTAL'] = $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'] = $params['ORI_YC'];
+                }
+                if (isset($params['ORI_VIP'])) {
+//                    $paramData['ORI_VIP_TOTAL'] = new Expression('ORI_VIP_TOTAL + '.$params['ORI_VIP']);
+                    $paramData['ORI_VIP_TOTAL'] = $params['ORI_VIP'];
+                }
+                if (isset($params['ORI_STANDARD'])) {
+                    $paramData['ORI_STANDARD_TOTAL'] = $params['ORI_STANDARD'];
+                }
+                if (isset($params['ORI_BD'])) {
+//                    $paramData['ORI_BD_TOTAL'] = new Expression('ORI_BD_TOTAL + '.$params['ORI_BD']);
+                    $paramData['ORI_BD_TOTAL'] = $params['ORI_BD'];
+                }
+                if (isset($params['ORI_TG'])) {
+//                    $paramData['ORI_TG_TOTAL'] = new Expression('ORI_TG_TOTAL + '.$params['ORI_TG']);
+                    $paramData['ORI_TG_TOTAL'] = $params['ORI_TG'];
+                }
+                if (isset($params['ORI_YJ'])) {
+//                    $paramData['ORI_YJ_TOTAL'] = new Expression('ORI_YJ_TOTAL + '.$params['ORI_YJ']);
+                    $paramData['ORI_YJ_TOTAL'] = $params['ORI_YJ'];
+                }
+                if (isset($params['ORI_GX'])) {
+//                    $paramData['ORI_GX_TOTAL'] = new Expression('ORI_GX_TOTAL + '.$params['ORI_GX']);
+                    $paramData['ORI_GX_TOTAL'] = $params['ORI_GX'];
+                }
+                if (isset($params['ORI_GL'])) {
+//                    $paramData['ORI_GL_TOTAL'] = new Expression('ORI_GL_TOTAL + '.$params['ORI_GL']);
+                    $paramData['ORI_GL_TOTAL'] = $params['ORI_GL'];
+                }
+                if (isset($params['ORI_BS'])) {
+                    $paramData['ORI_BS_TOTAL'] = $params['ORI_BS'];
+                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
+                }
+
+                if (isset($params['BONUS_TOTAL'])) {
+//                    $paramData['BONUS_TOTAL'] = new Expression('BONUS_TOTAL + '.$params['BONUS_TOTAL']);
+                    $paramData['BONUS_TOTAL'] = $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' => $amount,
+                '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'] ?? '',
+            ];
+            unset($userInfo, $oneUserBonus);
+            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, $amount);
+                }else {
+                    self::deductPeriodExchangePoints($userId, abs($amount));
+                }
+                FlowExchangePoints::insertOne($flowInsertData);
+            } elseif (strtolower($type) == 'cf') {
+                FlowCF::insertOne($flowInsertData);
+            } elseif (strtolower($type) == 'lx') {
+                FlowLX::insertOne($flowInsertData);
+            }
+            unset($flowInsertData);
+            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,201 +1,202 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/10/30
- * Time: 下午3:19
- */
-
-namespace common\helpers\user;
-
-use common\helpers\Date;
-use common\helpers\Form;
-use common\libs\lock\RedisLock;
-use common\models\FlowWallet;
-use common\models\Period;
-use common\models\UserWallet;
-use yii\base\Exception;
-use yii\db\Expression;
-
-class Cash {
-    const INCR_REDUCE = 0;      // 减少
-    const INCR_ADD = 1;         // 增加
-    const INCR_FREEZE = 2;      // 冻结
-    const INCR_UNFREEZE = 3;    // 解冻
-
-    const CASH_BALANCE_LOCK_KEY = 'Cash';
-
-    /**
-     * 获取当前可用余额
-     * @param $userId
-     * @return int|mixed
-     */
-    public static function getAvailableBalance($userId) {
-        $oneData = UserWallet::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        if ($oneData) {
-            return $oneData['CASH'];
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 改变会员的现金余额
-     * @param $userId
-     * @param $type
-     * @param $amount
-     * @param array $params
-     * @param bool $allowMinus
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function changeUserCash($userId, $type='CASH', $amount, $params = [], $allowMinus = false) {
-        if ($amount == 0) return true;
-        $period = Period::instance();
-        if (!isset($params['PERIOD_NUM'])) {
-            $periodNum = $period->getNowPeriodNum();
-        } else {
-            $periodNum = $params['PERIOD_NUM'];
-        }
-        $calcYearMonth = $period->getYearMonth($periodNum);
-        // redis加锁(防止并发余额数值不准确出错)
-        switch ($type) {
-            case 'CASH':
-                $lockKey = self::CASH_BALANCE_LOCK_KEY . $userId;
-                break;
-            default:
-                throw new Exception('流水类型错误');
-        }
-        if (RedisLock::instance()->lock($lockKey)) {
-            // 改变发奖
-            $paramData = [];
-            $oneUserBonusModel = UserWallet::findOne(['USER_ID' => $userId]);
-            if ($oneUserBonusModel) {
-                $paramData[$type] = new Expression($type.' + '.$amount);
-
-                $oneUserBonusModel->$type += $amount;
-                if ($oneUserBonusModel->$type < 0) {
-                    RedisLock::instance()->unlock($lockKey);
-                    throw new Exception('金额不足');
-                }
-                UserWallet::updateAll($paramData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-
-            } else {
-                $paramData = [
-                    'USER_ID'=>$userId,
-                    $type=>$amount,
-                    'UPDATED_AT'=>Date::nowTime()
-                ];
-                UserWallet::insertOne($paramData);
-
-//                $oneUserBonusModel = new UserWallet();
-//                $oneUserBonusModel->USER_ID = $userId;
-//                $oneUserBonusModel->$type = $amount;
-//                $oneUserBonusModel->UPDATED_AT = Date::nowTime();
-//                if (!$oneUserBonusModel->save()) {
-//                    throw new \yii\db\Exception(Form::formatErrorsForApi($oneUserBonusModel->getErrors()));
-//                }
-            }
-
-            unset($oneUserBonusModel,$paramData);
-            // 获取发放完成的奖金信息
-            $oneUserBonus = UserWallet::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-            // 记录流水
-            $flowInsertData = [
-                'USER_ID' => $userId,
-                'CALC_ID' => $params['CALC_ID'] ?? null,
-                'AMOUNT' => $amount,
-                'TOTAL' => $oneUserBonus[$type],
-                'IS_INCR' => $amount > 0 ? FlowWallet::INCR_ADD : FlowWallet::INCR_REDUCE,
-                'REMARK' => $params['REMARK'] ?? null,
-                'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $periodNum,
-                'CALC_MONTH' => $calcYearMonth,
-                'P_MONTH' => Date::ociToDate(),
-                'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
-                'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
-                'SORT' => $params['SORT'] ?? 0,
-                'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
-            ];
-            if (strtolower($type) == 'cash') FlowWallet::insertOne($flowInsertData);
-            unset($flowInsertData);
-            RedisLock::instance()->unlock($lockKey);
-        } else {
-            throw new Exception('流水产生错误');
-        }
-        return true;
-    }
-
-    /**
-     * 清空会员现金所有流水
-     * @param $userId
-     * @param array $params
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function clearAllCash($userId, $params = []) {
-        // 先查找会员的全部余额
-        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
-        // 如果没有会员余额数据,新建余额数据
-        if (!$userWallet) {
-            UserWallet::insertOne(['USER_ID' => $userId, 'CREATED_AT' => Date::nowTime()]);
-        } else {
-            $period = Period::instance();
-            $field = 'CASH';
-            if ($userWallet[$field]<=0) return;
-            $flowInsertData = [
-                'USER_ID' => $userId,
-                'CALC_ID' => $params['CALC_ID'] ?? null,
-                'AMOUNT' => -$userWallet[$field],
-                'TOTAL' => 0,
-                'IS_INCR' => FlowWallet::INCR_REDUCE,
-                'REMARK' => $params['REMARK'] ?? null,
-                'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $period->getNowPeriodNum(),
-                'CALC_MONTH' => $period->getNowYearMonth(),
-                'P_MONTH' => Date::ociToDate(),
-                'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
-                'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
-                'SORT' => $params['SORT'] ?? 0,
-                'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
-            ];
-            // 流水
-            if (strtolower($field) == 'cash') FlowWallet::insertOne($flowInsertData);
-
-            // 清空
-            $userWallet->CASH = 0;
-            if (!$userWallet->save()) {
-                throw new Exception(Form::formatErrorsForApi($userWallet->getErrors()));
-            }
-        }
-        FlowWallet::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-    }
-
-    /**
-     * 是否存在现金余额
-     * @param $userId
-     * @return bool
-     */
-    public static function hasCash($userId) {
-        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
-        if (!$userWallet) {
-            return false;
-        }
-        if (isset($userWallet['CASH']) && $userWallet['CASH'] > 0) {
-            return true;
-        }
-    }
-
-    /**
-     * 获取金额用于日志
-     * @param $userId
-     * @return array
-     */
-    public static function getLogData($userId){
-        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
-        $userName = Info::getUserNameByUserId($userId);
-        $data = [];
-        $data[$userId]['label'] = $userName.'余额';
-        $data[$userId]['value'] = '奖金'.self::getAvailableBalance($userId).',现金'.$userWallet['CASH'];
-        return $data;
-    }
-}
+<?php
+/**
+ * Created by PhpStorm.
+ * User: leo
+ * Date: 2018/10/30
+ * Time: 下午3:19
+ */
+
+namespace common\helpers\user;
+
+use common\helpers\Date;
+use common\helpers\Form;
+use common\libs\lock\RedisLock;
+use common\models\FlowWallet;
+use common\models\Period;
+use common\models\UserWallet;
+use yii\base\Exception;
+use yii\db\Expression;
+
+class Cash {
+    const INCR_REDUCE = 0;      // 减少
+    const INCR_ADD = 1;         // 增加
+    const INCR_FREEZE = 2;      // 冻结
+    const INCR_UNFREEZE = 3;    // 解冻
+
+    const CASH_BALANCE_LOCK_KEY = 'Cash';
+
+    /**
+     * 获取当前可用余额
+     * @param $userId
+     * @return int|mixed
+     */
+    public static function getAvailableBalance($userId) {
+        $oneData = UserWallet::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
+        if ($oneData) {
+            return $oneData['CASH'];
+        } else {
+            return 0;
+        }
+    }
+
+    /**
+     * 改变会员的现金余额
+     * @param $userId
+     * @param $type
+     * @param $amount
+     * @param array $params
+     * @param bool $allowMinus
+     * @return bool
+     * @throws Exception
+     * @throws \yii\db\Exception
+     */
+    public static function changeUserCash($userId, $type='CASH', $amount, $params = [], $allowMinus = false) {
+        if ($amount == 0) return true;
+        $period = Period::instance();
+        if (!isset($params['PERIOD_NUM'])) {
+            $periodNum = $period->getNowPeriodNum();
+        } else {
+            $periodNum = $params['PERIOD_NUM'];
+        }
+        $calcYearMonth = $period->getYearMonth($periodNum);
+        // redis加锁(防止并发余额数值不准确出错)
+        switch ($type) {
+            case 'CASH':
+                $lockKey = self::CASH_BALANCE_LOCK_KEY . $userId;
+                break;
+            default:
+                throw new Exception('流水类型错误');
+        }
+        if (RedisLock::instance()->lock($lockKey)) {
+            // 改变发奖
+            $paramData = [];
+            $oneUserBonusModel = UserWallet::findOne(['USER_ID' => $userId]);
+            if ($oneUserBonusModel) {
+                $paramData[$type] = new Expression($type.' + '.$amount);
+
+                $oneUserBonusModel->$type += $amount;
+                if ($oneUserBonusModel->$type < 0) {
+                    RedisLock::instance()->unlock($lockKey);
+                    throw new Exception('金额不足');
+                }
+                UserWallet::updateAll($paramData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
+
+            } else {
+                $paramData = [
+                    'USER_ID'=>$userId,
+                    $type=>$amount,
+                    'UPDATED_AT'=>Date::nowTime()
+                ];
+                UserWallet::insertOne($paramData);
+
+//                $oneUserBonusModel = new UserWallet();
+//                $oneUserBonusModel->USER_ID = $userId;
+//                $oneUserBonusModel->$type = $amount;
+//                $oneUserBonusModel->UPDATED_AT = Date::nowTime();
+//                if (!$oneUserBonusModel->save()) {
+//                    throw new \yii\db\Exception(Form::formatErrorsForApi($oneUserBonusModel->getErrors()));
+//                }
+            }
+
+            unset($oneUserBonusModel,$paramData);
+            // 获取发放完成的奖金信息
+            $oneUserBonus = UserWallet::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
+            // 记录流水
+            $flowInsertData = [
+                'USER_ID' => $userId,
+                'CALC_ID' => $params['CALC_ID'] ?? null,
+                'AMOUNT' => $amount,
+                'TOTAL' => $oneUserBonus[$type],
+                'IS_INCR' => $amount > 0 ? FlowWallet::INCR_ADD : FlowWallet::INCR_REDUCE,
+                'REMARK' => $params['REMARK'] ?? null,
+                'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $periodNum,
+                'CALC_MONTH' => $calcYearMonth,
+                'P_MONTH' => Date::ociToDate(),
+                'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
+                'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
+                'SORT' => $params['SORT'] ?? 0,
+                'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
+                'ORDER_SN' => $params['ORDER_SN'] ?? '',
+            ];
+            if (strtolower($type) == 'cash') FlowWallet::insertOne($flowInsertData);
+            unset($flowInsertData);
+            RedisLock::instance()->unlock($lockKey);
+        } else {
+            throw new Exception('流水产生错误');
+        }
+        return true;
+    }
+
+    /**
+     * 清空会员现金所有流水
+     * @param $userId
+     * @param array $params
+     * @throws Exception
+     * @throws \yii\db\Exception
+     */
+    public static function clearAllCash($userId, $params = []) {
+        // 先查找会员的全部余额
+        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
+        // 如果没有会员余额数据,新建余额数据
+        if (!$userWallet) {
+            UserWallet::insertOne(['USER_ID' => $userId, 'CREATED_AT' => Date::nowTime()]);
+        } else {
+            $period = Period::instance();
+            $field = 'CASH';
+            if ($userWallet[$field]<=0) return;
+            $flowInsertData = [
+                'USER_ID' => $userId,
+                'CALC_ID' => $params['CALC_ID'] ?? null,
+                'AMOUNT' => -$userWallet[$field],
+                'TOTAL' => 0,
+                'IS_INCR' => FlowWallet::INCR_REDUCE,
+                'REMARK' => $params['REMARK'] ?? null,
+                'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $period->getNowPeriodNum(),
+                'CALC_MONTH' => $period->getNowYearMonth(),
+                'P_MONTH' => Date::ociToDate(),
+                'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
+                'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
+                'SORT' => $params['SORT'] ?? 0,
+                'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
+            ];
+            // 流水
+            if (strtolower($field) == 'cash') FlowWallet::insertOne($flowInsertData);
+
+            // 清空
+            $userWallet->CASH = 0;
+            if (!$userWallet->save()) {
+                throw new Exception(Form::formatErrorsForApi($userWallet->getErrors()));
+            }
+        }
+        FlowWallet::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
+    }
+
+    /**
+     * 是否存在现金余额
+     * @param $userId
+     * @return bool
+     */
+    public static function hasCash($userId) {
+        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
+        if (!$userWallet) {
+            return false;
+        }
+        if (isset($userWallet['CASH']) && $userWallet['CASH'] > 0) {
+            return true;
+        }
+    }
+
+    /**
+     * 获取金额用于日志
+     * @param $userId
+     * @return array
+     */
+    public static function getLogData($userId){
+        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
+        $userName = Info::getUserNameByUserId($userId);
+        $data = [];
+        $data[$userId]['label'] = $userName.'余额';
+        $data[$userId]['value'] = '奖金'.self::getAvailableBalance($userId).',现金'.$userWallet['CASH'];
+        return $data;
+    }
+}

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

@@ -1,916 +1,916 @@
-<?php
-namespace common\models\forms;
-
-use common\components\Model;
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\helpers\Form;
-use common\helpers\user\Cash;
-use common\helpers\user\Reconsume;
-use common\helpers\user\Info;
-use common\models\DeclarationPackage;
-use common\models\DecOrder;
-use common\models\EmployLevel;
-use common\models\Order;
-use common\models\OrderGoods;
-use common\models\Period;
-use common\models\ReceiveAddress;
-use common\models\ReconsumePool;
-use common\models\ReconsumePoolFlow;
-use common\models\DeclarationLevel;
-use common\models\Region;
-use common\models\ShopGoods;
-use common\models\User;
-use common\models\UserInfo;
-use common\models\UserNetwork;
-use common\models\UserRelation;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class DeclarationForm extends Model
-{
-    public $type;
-    public $decLv;
-    public $decWay;
-    public $packageId;
-    public $goodsId;
-    public $goodsNum;
-    public $insertUserName;
-    public $password;
-    public $payPassword;
-    public $realName;
-    public $insertUserIdCard;
-    public $mobile;
-    public $address;
-    public $openBank;
-    public $bankAddress;
-    public $bankNo;
-    public $bankProvince;
-    public $bankCity;
-    public $bankCounty;
-    public $conUserName;
-    public $recUserName;
-    public $decUserName;
-    public $location;
-    public $consignee;
-    public $acceptMobile;
-    public $province;
-    public $city;
-    public $county;
-
-    // 传过来的全部数据
-    public $allData;
-    private $_decId;
-    public $_insertUserId;
-    private $_decAmount;
-    private $_decPv;
-    private $_orderGoods;
-
-    // 批量报单时添加会员的REDIS里面缓存的添加的会员资料
-    const REDIS_WAIT_ADD_USER = 'user:dec:waitAdd';
-
-    const TYPE_ZC = 'ZC';
-//    const TYPE_YH = 'YH';
-    const TYPE_ZG = 'ZG';
-    const TYPE_LS = 'LS';
-    const TYPE_FX = 'FX';
-
-//    private $_modelClass = null;
-    private $_oneOrder = null;
-    private $_userForm = null;
-    // 全部的上级(安置网和开拓网)
-    private $_tempParentUser = [];
-    // 全部的安置网上级
-    private $_tempNetworkParentUser = [];
-    // 全部的开拓网上级
-    private $_tempRelationParentUser = [];
-    private $_types = [
-        self::TYPE_ZC => [
-            'name' => '首购单',
-        ],
-//        self::TYPE_YH => [
-//            'class' => DeclarationYH::class,
-//            'table' => '{{%DECLARATION_YH}}',
-//            'name' => '优惠单',
-//        ],
-        self::TYPE_ZG => [
-            'name' => '升级增购单',
-        ],
-        self::TYPE_LS => [
-            'name' => '零售单',
-        ],
-        self::TYPE_FX => [
-            'name' => '复销单',
-        ],
-    ];
-
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['password','payPassword','type','decLv','decWay','packageId', 'insertUserName', 'realName', 'insertUserIdCard', 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo','bankProvince','bankCity','bankCounty','consignee','acceptMobile','province','city','county','decUserName', 'conUserName', 'recUserName', 'location'], 'trim'],
-            [['type','decLv','decWay','insertUserName', 'insertUserIdCard','decUserName'], 'required'],
-            [['type'], 'isType', 'on'=>['userDec', 'canDec']],
-            [['insertUserName'], 'isCanAddUser'],
-            [['decUserName'], 'issetDec'],
-            [['conUserName'], 'isConUserName'],
-            [['recUserName'], 'isRecUserName'],
-            [['location'], 'isLocation'],
-            [['insertUserIdCard'], 'isSameSystem'],
-        ];
-    }
-
-    public function attributeLabels()
-    {
-        return [
-            'type' => '报单类型',
-            'decLv' => '报单级别',
-            //'decPv' => '报单PV',
-            'decWay' => '报单方式',
-            'packageId' => '报单套餐',
-            'goodsId' => '商品ID',
-            'goodsNum' => '商品数量',
-            //'addType' => '新增会员方式',
-            'insertUserName' => '会员用户名',
-            'password' => '登陆密码',
-            'payPassword' => '支付密码',
-            'realName' => '会员姓名',
-            'insertUserIdCard' => '身份证号',
-            'mobile' => '手机号',
-            'address' => '地址',
-            'openBank' => '开户行',
-            'bankAddress' => '开户支行',
-            'bankNo' => '银行账号',
-            'bankProvince' => '银行省份',
-            'bankCity' => '银行城市',
-            'bankCounty' => '银行县区',
-            'conUserName' => '指导老师用户名',
-            'recUserName' => '开拓人用户名',
-            'decUserName' => '报单中心用户名',
-            'conUid' => '指导老师会员ID',
-            'recUid' => '开拓人会员ID',
-            'location' => '市场',
-            'consignee' => '收货人',
-            'acceptMobile' => '收货人手机',
-            'province' => '收货省',
-            'city' => '收货市',
-            'county' => '收货区县',
-            'address' => '收货详细地址',
-        ];
-    }
-
-    /**
-     * 指定场景
-     * @return array
-     */
-    public function scenarios()
-    {
-        $parentScenarios =  parent::scenarios();
-        $customScenarios = [
-            'userDec' => ['type','allData', 'decLv','decWay','insertUserName','password','payPassword', 'realName', 'insertUserIdCard', 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankProvince','bankCity','bankCounty', 'consignee','acceptMobile','province','city','county', 'conUserName', 'recUserName','decUserName', 'location'],
-            'canDec' => ['type', 'insertUserName', 'insertUserIdCard', 'conUserName', 'recUserName', 'location'],
-            'notFull' => ['type', 'insertUserName', 'conUserName', 'recUserName', 'location'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    /**
-     * 判断报单中心是否存在
-     * @param $attribute
-     */
-    public function issetDec($attribute){
-        if (!$decUser = User::find()->select('ID')->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])->asArray()->one()) {
-            $this->addError($attribute, '报单中心不存在');
-            return false;
-        } else {
-            // 判断报单中心是否在新加入会员的安置网上级中
-            $this->loopFindParentToNetwork($this->insertUserName);
-            //反转数组,in_array搜索错误
-            //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
-            $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
-//            var_dump($flipParent);
-//            echo $this->insertUserName.'=='.$this->decUserName;
-//            exit;
-            if (!isset($flipParent[$this->decUserName])) {
-                $this->addError($attribute, '为' . $this->insertUserName . '报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
-                return ;
-            }
-            $this->_decId = $decUser['ID'];
-        }
-    }
-
-    /**
-     * 判断指导老师
-     * @param $attribute
-     */
-    public function isConUserName($attribute){
-        if($this->type == self::TYPE_ZC){
-            // 从数据库查看接点会员是否在
-            if(!isset($this->_tempParentUser[$this->conUserName])){
-                $conUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->conUserName]);
-                if(!$conUserTemp){
-                    if($this->insertUserName){
-                        $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'不存在');
-                    } else {
-                        $this->addError($attribute, '指导老师'.$this->conUserName.'不存在');
-                    }
-                    return ;
-                }
-                $conUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($conUserTemp['USER_ID']);
-                $conUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($conUserTemp['USER_ID']);
-                $this->_tempParentUser[$this->conUserName] = [
-                    'USER_NAME' => $this->conUserName,
-                    'ZC_PV' => $conUserTemp['ZC_PV'],
-                    'CON_USER_NAME' => Info::getUserNameByUserId($conUserTemp['CON_UID']),
-                    'REC_USER_NAME' => Info::getUserNameByUserId($conUserTemp['REC_UID']),
-                    'CON_NUM' => $conUserTemp['CON_NUM'],
-                    'REC_NUM' => $conUserTemp['REC_NUM'],
-                    'SYSTEM_ID' => $conUserTemp['SYSTEM_ID'],
-                    'LOCATION' => UserNetwork::getLocation($conUserTemp['USER_ID'], $conUserTemp['CON_UID']),
-                ];
-                // 把该会员下面的5个区是否存在会员都付上
-                for($i=1;$i<=5;$i++){
-                    $this->_tempParentUser[$this->conUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($conUserTemp['USER_ID'], $i);
-                }
-            }
-            $conUser = $this->_tempParentUser[$this->conUserName];
-            // 判断接点会员的下级会员是否大于三个,如果大于三个则不允许
-            if($conUser['CON_NUM'] >= 3){
-                if($this->insertUserName){
-                    $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'下级点位已满');
-                } else {
-                    $this->addError($attribute, '指导老师'.$this->conUserName.'下级点位已满');
-                }
-                return;
-            }
-            if($this->insertUserName){
-                // 把自己加入到临时上级会员数组中
-                $this->_tempParentUser[$this->insertUserName] = [
-                    'USER_NAME' => $this->insertUserName,
-                    //'ZC_PV' => $this->decPv,
-                    'CON_USER_NAME' => $this->conUserName,
-                    'REC_USER_NAME' => $this->recUserName,
-                    'CON_NUM' => 0,
-                    'REC_NUM' => 0,
-                    'SYSTEM_ID' => $conUser['SYSTEM_ID'],
-                    'LOCATION' => $this->location,
-                    'LOCATION1' => 0,
-                    'LOCATION2' => 0,
-                    'LOCATION3' => 0,
-                    'LOCATION4' => 0,
-                    'LOCATION5' => 0,
-                ];
-            }
-
-        }
-    }
-
-    /**
-     * 判断开拓人
-     * @param $attribute
-     */
-    public function isRecUserName($attribute){
-        if($this->type == self::TYPE_ZC){
-            // 开拓人
-            if(!isset($this->_tempParentUser[$this->recUserName])){
-                $recUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->recUserName]);
-                if(!$recUserTemp){
-                    if($this->insertUserName){
-                        $this->addError($attribute, '为'.$this->insertUserName.'报单,开拓人'.$this->recUserName.'不存在');
-                    } else {
-                        $this->addError($attribute, '开拓人'.$this->recUserName.'不存在');
-                    }
-
-                    return ;
-                }
-                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
-                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
-                $this->_tempParentUser[$this->recUserName] = [
-                    'USER_NAME' => $this->recUserName,
-                    'ZC_PV' => $recUserTemp['ZC_PV'],
-                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
-                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
-                    'CON_NUM' => $recUserTemp['CON_NUM'],
-                    'REC_NUM' => $recUserTemp['REC_NUM'],
-                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
-                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
-                ];
-                // 把该会员下面的5个区是否存在会员都付上
-                for($i=1;$i<=5;$i++){
-                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
-                }
-            }
-            $recUser = $this->_tempParentUser[$this->recUserName];
-            $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;
-
-            // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
-            if($this->insertUserName) {
-                $this->loopFindParentToNetwork($this->insertUserName);
-                if (!$this->recUserIsInNetworkParent()) {
-                    $this->addError($attribute, '为' . $this->insertUserName . '报单,开拓人' . $this->recUserName . '不在' . $this->insertUserName . '的安置网上级中');
-                    return ;
-                }
-            }
-
-            // 把自己加入到临时上级会员数组中
-            $this->_tempParentUser[$this->insertUserName] = [
-                'USER_NAME' => $this->insertUserName,
-                //'ZC_PV' => $this->decPv,
-                'CON_USER_NAME' => $this->conUserName,
-                'REC_USER_NAME' => $this->recUserName,
-                'CON_NUM' => 0,
-                'REC_NUM' => 0,
-                'SYSTEM_ID' => $recUser['SYSTEM_ID'],
-                'LOCATION' => $this->location,
-                'LOCATION1' => 0,
-                'LOCATION2' => 0,
-                'LOCATION3' => 0,
-                'LOCATION4' => 0,
-                'LOCATION5' => 0,
-            ];
-        }
-
-    }
-
-    /**
-     * 循环把所有新加入的会员的上级加入到临时变量中
-     * @param null $conUserName
-     * @return bool
-     */
-    private function loopFindParentToNetwork($conUserName = null) {
-        if($conUserName == null ){
-            $conUserName = $this->insertUserName;
-        }
-        $findUserKey = array_search($conUserName, array_column($this->allData, 'insertUserName'));
-        // 如果有这个新加入的会员,则查找其上级接点
-        if($findUserKey !== false){
-            if(strtoupper($this->allData[$findUserKey]['type']) == 'ZC'){
-                $this->_tempNetworkParentUser[$this->insertUserName][] = $this->allData[$findUserKey]['conUserName'];
-                $this->loopFindParentToNetwork($this->allData[$findUserKey]['conUserName']);
-            }
-        }
-        // 如果没有这个新加入的接点,
-        else {
-            if($this->insertUserName == $conUserName){
-                $this->addError('recUserName', '新加入的会员不存在');
-                return false;
-            }
-            // 去数据库里查找这个会员的所有上级
-//            $allParentUser = UserNetwork::find()->select('PUI.USER_NAME')->where('UI.USER_NAME=:USER_NAME', [':USER_NAME'=>$conUserName])->from(UserNetwork::tableName().' AS UN')->join('LEFT JOIN', UserInfo::tableName().' AS UI', 'UN.USER_ID=UI.USER_ID')->join('LEFT JOIN', UserInfo::tableName().' AS PUI', 'UN.PARENT_UID=PUI.USER_ID')->orderBy('PUI.NETWORK_DEEP DESC')->asArray()->all();
-            $baseUser = Info::getBaseUserByUserName($conUserName);
-            $userNetworkInfo = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $baseUser['ID']]);
-            unset($baseUser);
-            $allParentUserIdsArr = explode(',', $userNetworkInfo['PARENT_UIDS']);
-            unset($userNetworkInfo);
-            $allParentUserIds = array_reverse($allParentUserIdsArr);
-            unset($allParentUserIdsArr);
-            if($allParentUserIds){
-                foreach($allParentUserIds as $parentUserId) {
-                    $parentBaseUser = Info::getBaseUserById($parentUserId);
-                    $this->_tempNetworkParentUser[$this->insertUserName][] = $parentBaseUser['USER_NAME'] ;
-
-                    unset($parentUserId, $parentBaseUser);
-                }
-            }
-            unset($allParentUserIds);
-        }
-        return true;
-    }
-
-    /**
-     * 开拓人是否在新加入会员的上级中
-     * @return bool
-     */
-    private function recUserIsInNetworkParent(){
-        return in_array($this->recUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
-    }
-
-    /**
-     * 判断区域是否正确
-     * @param $attribute
-     */
-    public function isLocation($attribute){
-        if($this->type == self::TYPE_ZC){
-            if(!in_array($this->location, [1, 2, 3])){
-                $this->addError($attribute, '市场必须在第1市场、第2市场或第三3市场');
-            }
-            $conUser = $recUser = null;
-            if(isset($this->_tempParentUser[$this->conUserName])){
-                $conUser = $this->_tempParentUser[$this->conUserName];
-            }
-            if(isset($this->_tempParentUser[$this->recUserName])){
-                $recUser = $this->_tempParentUser[$this->recUserName];
-            }
-            if($conUser){
-                // 判断指导老师相应的区位是否已满
-                if($conUser['LOCATION'.$this->location]){
-                    if($this->insertUserName){
-                        $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'的第'.$this->location.'市场已存在会员');
-                    } else {
-                        $this->addError($attribute, '指导老师'.$this->conUserName.'的第'.$this->location.'市场已存在会员');
-                    }
-                    return;
-                }
-                //市场顺序判断
-//                if($conUser['CON_NUM'] == 0 && $this->location != 1){
-//                    if($this->insertUserName){
-//                        $this->addError($attribute, '为'.$this->insertUserName.'报单,市场必须为指导老师'.$this->conUserName.'下第一市场');
-//                    } else {
-//                        $this->addError($attribute, '市场必须为指导老师'.$this->conUserName.'下第一市场');
-//                    }
-//                    return;
-//                }
-//                if($conUser['CON_NUM'] == 1 && $this->location == 3){
-//                    if($this->insertUserName){
-//                        $this->addError($attribute, '为'.$this->insertUserName.'报单,市场必须为指导老师'.$this->conUserName.'第二市场');
-//                    } else {
-//                        $this->addError($attribute, '市场必须为指导老师'.$this->conUserName.'第二市场');
-//                    }
-//                    return;
-//                }
-                $this->_tempParentUser[$this->conUserName]['CON_NUM'] += 1;
-                $this->_tempParentUser[$this->conUserName]['LOCATION'.$this->location] = true;
-            }
-        }
-    }
-
-    /**
-     * 判断会员是否可加入(通过redis结合数据库判断上级会员的情况)
-     * @param $attribute
-     */
-    public function isCanAddUser($attribute){
-        if($this->type == self::TYPE_ZC){
-            // 从数据库查看接点会员是否在
-            if(!isset($this->_tempParentUser[$this->conUserName])){
-                $conUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->conUserName]);
-                if(!$conUserTemp){
-                    $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'不存在');
-                    return ;
-                }
-                $conUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($conUserTemp['USER_ID']);
-                $conUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($conUserTemp['USER_ID']);
-                $this->_tempParentUser[$this->conUserName] = [
-                    'USER_NAME' => $this->conUserName,
-                    //'ZC_PV' => $conUserTemp['ZC_PV'],
-                    'CON_USER_NAME' => Info::getUserNameByUserId($conUserTemp['CON_UID']),
-                    'REC_USER_NAME' => Info::getUserNameByUserId($conUserTemp['REC_UID']),
-                    'CON_NUM' => $conUserTemp['CON_NUM'],
-                    'REC_NUM' => $conUserTemp['REC_NUM'],
-                    'SYSTEM_ID' => $conUserTemp['SYSTEM_ID'],
-                    'LOCATION' => UserNetwork::getLocation($conUserTemp['USER_ID'], $conUserTemp['CON_UID']),
-                ];
-                // 把该会员下面的5个区是否存在会员都付上
-                for($i=1;$i<=5;$i++){
-                    $this->_tempParentUser[$this->conUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($conUserTemp['USER_ID'], $i);
-                }
-            }
-            $conUser = $this->_tempParentUser[$this->conUserName];
-
-            // 开拓人
-            if(!isset($this->_tempParentUser[$this->recUserName])){
-                $recUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->recUserName]);
-                if(!$recUserTemp){
-                    $this->addError($attribute, '为'.$this->insertUserName.'报单,开拓人'.$this->recUserName.'不存在');
-                    return ;
-                }
-                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
-                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
-                $this->_tempParentUser[$this->recUserName] = [
-                    'USER_NAME' => $this->recUserName,
-                    //'ZC_PV' => $recUserTemp['ZC_PV'],
-                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
-                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
-                    'CON_NUM' => $recUserTemp['CON_NUM'],
-                    'REC_NUM' => $recUserTemp['REC_NUM'],
-                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
-                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
-                ];
-                // 把该会员下面的5个区是否存在会员都付上
-                for($i=1;$i<=5;$i++){
-                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
-                }
-            }
-            $recUser = $this->_tempParentUser[$this->recUserName];
-
-            // 判断接点会员的下级会员是否大于三个,如果大于三个则不允许
-            if($conUser['CON_NUM'] >= 3){
-                $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'下级点位已满');
-                return;
-            }
-            // 判断指导老师相应的区位是否已满
-            if($conUser['LOCATION'.$this->location]){
-                $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'该市场已存在会员');
-                return;
-            }
-//            if($conUser['CON_NUM'] == 0 && $this->location != 1){
-//                $this->addError($attribute, '为'.$this->insertUserName.'报单,市场必须为指导老师'.$this->conUserName.'下第一市场');
-//                return;
-//            }
-
-            // 把指导老师的变量的相关数量增加数量
-//            $this->_tempParentUser[$this->conUserName]['CON_NUM'] += 1;
-//            $this->_tempParentUser[$this->conUserName]['LOCATION'.$this->location] = true;
-//            $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;
-
-            // 把自己加入到临时上级会员数组中
-            $this->_tempParentUser[$this->insertUserName] = [
-                'USER_NAME' => $this->insertUserName,
-                //'ZC_PV' => $this->decPv,
-                'CON_USER_NAME' => $this->conUserName,
-                'REC_USER_NAME' => $this->recUserName,
-                'CON_NUM' => 0,
-                'REC_NUM' => 0,
-                'SYSTEM_ID' => $recUser['SYSTEM_ID'],
-                'LOCATION' => $this->location,
-                'LOCATION1' => 0,
-                'LOCATION2' => 0,
-                'LOCATION3' => 0,
-                'LOCATION4' => 0,
-                'LOCATION5' => 0,
-            ];
-        }
-    }
-
-    /**
-     * 报单类型
-     * @param $attribute
-     * @param $params
-     */
-    public function isType($attribute, $params){
-        if(array_key_exists($this->type, $this->_types)){
-            if($this->type == self::TYPE_ZC){
-                if($this->scenario == 'userDec'){
-                    if(!$this->insertUserName) $this->addError($attribute, '首购必须填写加入会员编号');
-                }
-                if(!$this->insertUserName) $this->addError($attribute, '首购必须填写加入会员编号');
-                if(!$this->insertUserIdCard) $this->addError($attribute, '首购必须填写加入会员的身份证号');
-                if(!$this->conUserName) $this->addError($attribute, '首购必须填写加入会员的指导老师编号');
-                if(!$this->recUserName) $this->addError($attribute, '首购必须填写加入会员的开拓人编号');
-                if(!$this->location) $this->addError($attribute, '首购必须填写加入会员的市场');
-            }
-        } else {
-            $this->addError($attribute, '报单类型不正确');
-        }
-    }
-
-    /**
-     * 检验相同身份证 会员是否同一体系内(接点)
-     * @param $attribute
-     */
-    public function isSameSystem($attribute){
-        if(isset($this->_tempParentUser[$this->conUserName])){
-            // 新加入会员的身份证号对应网内的其他会员
-            $otherUser = User::findAllAsArray("ID_CARD=:ID_CARD AND IS_UNION=0 AND DELETED=0 AND (ID_CARD_PREFIX IS NULL OR ID_CARD_PREFIX='')", [':ID_CARD'=>$this->insertUserIdCard]);
-            if(count($otherUser)>=7){
-                $this->addError($attribute, '同一个身份证限制只能报7单');
-            }
-            if($otherUser){
-                $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
-                $isExsit = false;
-                foreach ($otherUser as $conUser){
-                    if(isset($flipParent[$conUser['USER_NAME']])){
-                        $isExsit = true;
-                        break;
-                    }
-                }
-                if (!$isExsit) {
-                    $this->addError($attribute, '为' . $this->insertUserName . '报单,身份证号码相同的会员'.$otherUser[0]['USER_NAME'].'不在' . $this->insertUserName . '的安置网上级中');
-                    return ;
-                }
-            }
-        } else {
-            $this->addError($attribute, '为'.$this->insertUserName.'报单,接点人'.$this->conUserName.'不存在');
-        }
-    }
-
-    /**
-     * 添加报单
-     * @param $allData
-     * @return bool|null
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public function add($allData){
-        if(!$this->validate()){
-            return null;
-        }
-
-        // 首购单,需要添加会员操作
-        if($this->type == self::TYPE_ZC){
-            if (preg_match("/[\x7f-\xff]/", $this->insertUserName)) {  //判断字符串中是否有中文
-                throw new Exception('会员编号中不能含有汉字');
-            }
-            //报单商品及PV判断
-            $decLevelConfig = Cache::getDecLevelConfig();
-            $decLevel = $decLevelConfig[$this->decLv];
-            $toDecLevel = $this->decLv;
-            if(!$this->decLv){
-                throw new Exception('请选择报单级别');
-            }
-            if($this->decWay==1) {
-                $decPackage = DeclarationPackage::findOneAsArray('ID=:ID', [':ID'=>$this->packageId]);
-                $this->_decAmount = $decPackage['AMOUNT'];
-                $this->_decPv = $decPackage['PV'];
-                $this->_orderGoods[] = [
-                    'GOODS_ID' => $this->packageId,
-                    'PRICE' => $this->_decAmount,
-                    'REAL_PRICE' => $this->_decAmount,
-                    'PV' => $this->_decPv,
-                    'REAL_PV' => $this->_decPv,
-                    'BUY_NUMS' => 1,
-                    'SKU_CODE' => $decPackage['PACKAGE_NO'],
-                    'GOODS_TITLE' => $decPackage['PACKAGE_NAME']
-                ];
-                // 更改库存和状态
-                $data = DeclarationPackage::find()->where(['ID' => $decPackage['ID']])->one();
-                $data->STORE_NUMS = $data->STORE_NUMS - 1;
-                if($data->STORE_NUMS <= 0){
-                    $data->STATUS = 0;
-                    $data->UPDATED_AT = Date::nowTime();
-                }
-                $data->update();
-            }else{
-                $ids = $this->goodsId;
-                $totalAmount = 0;
-                $totalPv = 0;
-                foreach ($this->goodsNum as $k => $v) {
-                    if ($v) {
-                        $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
-                        if (!$goods) {
-                            throw new Exception('商品已下架');
-                            return;
-                        }
-                        if($goods['STORE_NUMS']>0){
-                            $totalAmount += $goods['SELL_PRICE'] * intval($v);
-                            $totalPv += $goods['PRICE_PV'] * intval($v);
-                            $this->_orderGoods[] = [
-                                'GOODS_ID' => $goods['ID'],
-                                'PRICE' => $goods['SELL_PRICE'],
-                                'REAL_PRICE' => $goods['SELL_PRICE'],
-                                'PV' => $goods['PRICE_PV'],
-                                'REAL_PV' => $goods['PRICE_PV'],
-                                'POINT' => $goods['POINT'],
-                                'BUY_NUMS' => intval($v),
-                                'SKU_CODE' => $goods['GOODS_NO'],
-                                'GOODS_TITLE' => $goods['GOODS_NAME']
-                            ];
-                            // 更改库存和状态
-                            $data = ShopGoods::find()->where(['ID' => $goods['ID']])->one();
-                            $data->STORE_NUMS = $data->STORE_NUMS - intval($v);
-                            if($data->STORE_NUMS <= 0){
-                                $data->STATUS = 0;
-                                $data->UPDATED_AT = Date::nowTime();
-                            }
-                            $data->update();
-                        }
-                    }
-                }
-                if($totalPv<$decLevel['PERF']){
-                    throw new Exception('自选商品总PV不能小于所选报单级别PV');
-                }
-                foreach ($decLevelConfig as $key=>$val){
-                    if($totalPv>=$val['PERF']){
-                        $toDecLevel = $key;
-                    }
-                }
-                if($this->decLv!=$toDecLevel){
-                    throw new Exception('自选商品总PV不能超过已选级别下一个级别的PV值');
-                }
-                $this->_decAmount = $totalAmount;
-                $this->_decPv = $totalPv;
-            }
-            //看现金余额是否充足
-            $loginUserId = \Yii::$app->user->id;
-            if (Cash::getAvailableBalance($loginUserId) < $this->_decAmount){
-                throw new Exception('报单人现金不足,无法完成报单');
-            }
-
-            if(!($zcResult = $this->addUser($allData))) {
-                throw new Exception(Form::formatErrorsForApi($this->_userForm->getErrors()));
-            }
-            if(!($decResult = $this->addDecOrder())) {
-                throw new Exception(Form::formatErrorsForApi($decResult->getErrors()));
-            }
-        }
-        return true;
-    }
-
-    /**
-     * 添加会员
-     * @param $allData
-     * @return bool|UserInfo|null
-     * @throws \yii\db\Exception
-     */
-    public function addUser($allData){
-        $period = Period::instance();
-        $userPasswd = $this->password;
-        $userPayPasswd = $this->payPassword;
-        // 如果身份证信息有误,或不足6位,并且没有手动填写密码,就用111111
-        if (Info::simpleIdCardCheck($this->insertUserIdCard)) {
-            if (empty($userPasswd)) {
-                $userPasswd = Info::passwordGenerator($this->insertUserIdCard,$this->insertUserName);
-            }
-            if (empty($userPayPasswd)) {
-                $userPayPasswd = Info::passwordGenerator($this->insertUserIdCard,$this->insertUserName);
-            }
-        } else {
-            if (empty($userPasswd)) {
-                $userPasswd = '111111';
-            }
-            if (empty($userPayPasswd)) {
-                $userPayPasswd = '111111';
-            }
-        }
-
-        // 增加会员
-        $user = new User();
-        $user->USER_NAME = $this->insertUserName;
-        $user->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($userPasswd);
-        $user->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($userPayPasswd);
-        $user->NATION = 0;
-        $user->REAL_NAME = $this->realName;
-        $user->ID_CARD = $this->insertUserIdCard;
-        $user->MOBILE = $this->mobile;
-        $user->ADDRESS = $this->address ? $this->address : '无';
-        $user->OPEN_BANK = $this->openBank;
-        $user->BANK_ADDRESS = $this->bankAddress;
-        $user->BANK_NO = $this->bankNo;
-        $user->BANK_PROVINCE = $this->bankProvince ?? 0;
-        $user->BANK_CITY = $this->bankCity ?? 0;
-        $user->BANK_COUNTY = $this->bankCounty ?? 0;
-        $user->CREATED_AT = Date::nowTime();
-        $user->STATUS = 1;
-        $user->DEC_LV = $this->decLv;
-        $user->LAST_DEC_LV = $this->decLv;
-        $user->EMP_LV = EmployLevel::getDefaultLevelId();
-        $user->PROVINCE = intval($this->province) ?? 0;
-        $user->CITY = intval($this->city) ?? 0;
-        $user->COUNTY = intval($this->county) ?? 0;
-        $user->AVATAR = 'avatar/1.png';
-        $user->IS_DEC = 0;
-        $user->DEC_ID = $this->_decId ?? null;
-        $user->DEC_ROLE_ID = $this->decRoleId ?? null;
-        $user->PERIOD_AT = $period->getNowPeriodNum();
-        $user->IS_DIRECT_SELLER = 0;
-        $user->VERIFIED = 1;
-        $user->VERIFIED_AT = Date::nowTime();
-
-        if (!$user->save()) {
-            throw new Exception(Form::formatErrorsForApi($user->getErrors()));
-        }
-
-        $this->_insertUserId = $user->ID;
-        $userForm = new UserForm();
-        $this->_userForm = $userForm;
-        $userForm->scenario = 'addWithUserName';
-        $userForm->userId = $this->_insertUserId;
-        $userForm->userName = $this->insertUserName;
-        $userForm->zcPv = $this->_decPv;
-        $userForm->zcAmount = $this->_decAmount;
-        $userForm->conUserName = $this->conUserName;
-        $userForm->recUserName = $this->recUserName;
-        $userForm->location = $this->location;
-        $userForm->idCard = $this->insertUserIdCard;
-        $userForm->allData = $allData;
-        if(!$userForm->validate()){
-            $this->addErrors($userForm->getErrors());
-            return false;
-        }
-        if($result = $userForm->add()){
-            return $result;
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * 添加报单订单
-     * @return bool|UserInfo|null
-     * @throws \yii\db\Exception
-     */
-    public function addDecOrder(){
-        $periodObj = Period::instance();
-        $nowPeriodNum = $periodObj->getNowPeriodNum();
-        $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
-
-        $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
-        // 加入报单信息
-        $decOrderModel = new DecOrder();
-        $decOrderModel->DEC_SN = 'DS'.$ord;
-        $decOrderModel->ORDER_SN = 'OS'.$ord;
-        $decOrderModel->TYPE = $this->type;
-        $decOrderModel->USER_ID = \Yii::$app->user->id;
-        $decOrderModel->TO_USER_ID = $this->_insertUserId;
-        $decOrderModel->DEC_AMOUNT = $this->_decAmount;
-        $decOrderModel->DEC_PV = $this->_decPv;
-        $decOrderModel->PERIOD_NUM = $nowPeriodNum;
-        $decOrderModel->CALC_MONTH = $nowCalcMonth;
-        $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
-        $decOrderModel->PAID_WALLET = 'cash';
-        $decOrderModel->CON_USER_ID = Info::getUserIdByUserName($this->conUserName);
-        $decOrderModel->REC_USER_ID = Info::getUserIdByUserName($this->recUserName);
-        $decOrderModel->DEC_ID = $this->_decId;
-        $decOrderModel->IS_DEL = 0;
-        $decOrderModel->CREATED_AT = Date::nowTime();
-        if(!$decOrderModel->save()){
-            throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
-        }
-
-        // 加入订单信息
-        $warehouse = Region::getWarehouseByCode($this->province);//仓库
-        if(!$warehouse){
-            throw new Exception('地区暂时不支持配送,具体联系客服');
-        }
-        $orderModel = new Order();
-        $orderModel->SN = 'OS'.$ord;
-        $orderModel->DEC_SN = 'DS'.$ord;
-        $orderModel->ORDER_TYPE = $this->type;
-        $orderModel->USER_ID = $this->_insertUserId;
-        $orderModel->USER_NAME = $this->insertUserName;
-        $orderModel->ORDER_AMOUNT = $this->_decAmount;
-        $orderModel->PV = $this->_decPv;
-        $orderModel->PAY_AMOUNT = $this->_decAmount;
-        $orderModel->PAY_PV = $this->_decPv;
-        $orderModel->PAY_AT = Date::nowTime();
-        $orderModel->PAY_TYPE = 'cash';
-        $orderModel->PERIOD_NUM = $nowPeriodNum;
-        $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
-        $orderModel->FREIGHT = 0;
-        $orderModel->PAY_FREIGHT = 0;
-        $orderModel->CONSIGNEE = $this->consignee;
-        $orderModel->MOBILE = $this->acceptMobile;
-        $orderModel->PROVINCE = $this->province;
-        $orderModel->CITY = $this->city;
-        $orderModel->COUNTY = intval($this->county) ?? 0;
-        $orderModel->ADDRESS = $this->address;
-        $orderModel->WAREHOUSE = $warehouse;
-        $orderModel->STATUS = 1;
-        $orderModel->CREATED_AT = Date::nowTime();
-        $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
-        if(!$orderModel->save()){
-            throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
-        }
-        // 加入商品到订单商品表
-        foreach($this->_orderGoods as $key=>$value){
-            $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
-            $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
-        }
-        OrderGoods::batchInsert($this->_orderGoods);
-
-        //写入收货地址信息
-        $addressModel = new ReceiveAddress();
-        $addressModel->USER_ID = $this->_insertUserId;
-        $addressModel->USER_NAME = $this->insertUserName;
-        $addressModel->CONSIGNEE = $this->consignee;
-        $addressModel->MOBILE = $this->acceptMobile;
-        $addressModel->PROVINCE = $this->province;
-        $addressModel->CITY = $this->city;
-        $addressModel->COUNTY = intval($this->county) ?? 0;
-        $addressModel->ADDRESS = $this->address;
-        $addressModel->IS_DEFAULT = 1;
-        if(!$addressModel->save()){
-            throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
-        }
-        //扣报单人现金钱包
-        Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'报单']);
-
-        return $addressModel;
-    }
-
-
-
-    /**
-     * 删单
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function delete(){
-        if(!$this->validate()){
-            return false;
-        }
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $oneOrder = $this->_oneOrder;
-            // 首购单要删除会员
-            if($this->type == self::TYPE_ZC){
-                UserInfo::deleteUser($oneOrder['TO_USER_ID']);
-            }
-            // 如果是复销单的话,还需要考虑给会员的复销池减去金额
-            elseif($this->type == self::TYPE_FX){
-                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('delete', $e->getMessage());
-            return false;
-        }
-        return true;
-    }
-
-}
+<?php
+namespace common\models\forms;
+
+use common\components\Model;
+use common\helpers\Cache;
+use common\helpers\Date;
+use common\helpers\Form;
+use common\helpers\user\Cash;
+use common\helpers\user\Reconsume;
+use common\helpers\user\Info;
+use common\models\DeclarationPackage;
+use common\models\DecOrder;
+use common\models\EmployLevel;
+use common\models\Order;
+use common\models\OrderGoods;
+use common\models\Period;
+use common\models\ReceiveAddress;
+use common\models\ReconsumePool;
+use common\models\ReconsumePoolFlow;
+use common\models\DeclarationLevel;
+use common\models\Region;
+use common\models\ShopGoods;
+use common\models\User;
+use common\models\UserInfo;
+use common\models\UserNetwork;
+use common\models\UserRelation;
+use yii\base\Exception;
+
+/**
+ * Login form
+ */
+class DeclarationForm extends Model
+{
+    public $type;
+    public $decLv;
+    public $decWay;
+    public $packageId;
+    public $goodsId;
+    public $goodsNum;
+    public $insertUserName;
+    public $password;
+    public $payPassword;
+    public $realName;
+    public $insertUserIdCard;
+    public $mobile;
+    public $address;
+    public $openBank;
+    public $bankAddress;
+    public $bankNo;
+    public $bankProvince;
+    public $bankCity;
+    public $bankCounty;
+    public $conUserName;
+    public $recUserName;
+    public $decUserName;
+    public $location;
+    public $consignee;
+    public $acceptMobile;
+    public $province;
+    public $city;
+    public $county;
+
+    // 传过来的全部数据
+    public $allData;
+    private $_decId;
+    public $_insertUserId;
+    private $_decAmount;
+    private $_decPv;
+    private $_orderGoods;
+
+    // 批量报单时添加会员的REDIS里面缓存的添加的会员资料
+    const REDIS_WAIT_ADD_USER = 'user:dec:waitAdd';
+
+    const TYPE_ZC = 'ZC';
+//    const TYPE_YH = 'YH';
+    const TYPE_ZG = 'ZG';
+    const TYPE_LS = 'LS';
+    const TYPE_FX = 'FX';
+
+//    private $_modelClass = null;
+    private $_oneOrder = null;
+    private $_userForm = null;
+    // 全部的上级(安置网和开拓网)
+    private $_tempParentUser = [];
+    // 全部的安置网上级
+    private $_tempNetworkParentUser = [];
+    // 全部的开拓网上级
+    private $_tempRelationParentUser = [];
+    private $_types = [
+        self::TYPE_ZC => [
+            'name' => '首购单',
+        ],
+//        self::TYPE_YH => [
+//            'class' => DeclarationYH::class,
+//            'table' => '{{%DECLARATION_YH}}',
+//            'name' => '优惠单',
+//        ],
+        self::TYPE_ZG => [
+            'name' => '升级增购单',
+        ],
+        self::TYPE_LS => [
+            'name' => '零售单',
+        ],
+        self::TYPE_FX => [
+            'name' => '复销单',
+        ],
+    ];
+
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['password','payPassword','type','decLv','decWay','packageId', 'insertUserName', 'realName', 'insertUserIdCard', 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo','bankProvince','bankCity','bankCounty','consignee','acceptMobile','province','city','county','decUserName', 'conUserName', 'recUserName', 'location'], 'trim'],
+            [['type','decLv','decWay','insertUserName', 'insertUserIdCard','decUserName'], 'required'],
+            [['type'], 'isType', 'on'=>['userDec', 'canDec']],
+            [['insertUserName'], 'isCanAddUser'],
+            [['decUserName'], 'issetDec'],
+            [['conUserName'], 'isConUserName'],
+            [['recUserName'], 'isRecUserName'],
+            [['location'], 'isLocation'],
+            [['insertUserIdCard'], 'isSameSystem'],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'type' => '报单类型',
+            'decLv' => '报单级别',
+            //'decPv' => '报单PV',
+            'decWay' => '报单方式',
+            'packageId' => '报单套餐',
+            'goodsId' => '商品ID',
+            'goodsNum' => '商品数量',
+            //'addType' => '新增会员方式',
+            'insertUserName' => '会员用户名',
+            'password' => '登陆密码',
+            'payPassword' => '支付密码',
+            'realName' => '会员姓名',
+            'insertUserIdCard' => '身份证号',
+            'mobile' => '手机号',
+            'address' => '地址',
+            'openBank' => '开户行',
+            'bankAddress' => '开户支行',
+            'bankNo' => '银行账号',
+            'bankProvince' => '银行省份',
+            'bankCity' => '银行城市',
+            'bankCounty' => '银行县区',
+            'conUserName' => '指导老师用户名',
+            'recUserName' => '开拓人用户名',
+            'decUserName' => '报单中心用户名',
+            'conUid' => '指导老师会员ID',
+            'recUid' => '开拓人会员ID',
+            'location' => '市场',
+            'consignee' => '收货人',
+            'acceptMobile' => '收货人手机',
+            'province' => '收货省',
+            'city' => '收货市',
+            'county' => '收货区县',
+            'address' => '收货详细地址',
+        ];
+    }
+
+    /**
+     * 指定场景
+     * @return array
+     */
+    public function scenarios()
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            'userDec' => ['type','allData', 'decLv','decWay','insertUserName','password','payPassword', 'realName', 'insertUserIdCard', 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankProvince','bankCity','bankCounty', 'consignee','acceptMobile','province','city','county', 'conUserName', 'recUserName','decUserName', 'location'],
+            'canDec' => ['type', 'insertUserName', 'insertUserIdCard', 'conUserName', 'recUserName', 'location'],
+            'notFull' => ['type', 'insertUserName', 'conUserName', 'recUserName', 'location'],
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * 判断报单中心是否存在
+     * @param $attribute
+     */
+    public function issetDec($attribute){
+        if (!$decUser = User::find()->select('ID')->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])->asArray()->one()) {
+            $this->addError($attribute, '报单中心不存在');
+            return false;
+        } else {
+            // 判断报单中心是否在新加入会员的安置网上级中
+            $this->loopFindParentToNetwork($this->insertUserName);
+            //反转数组,in_array搜索错误
+            //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
+            $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
+//            var_dump($flipParent);
+//            echo $this->insertUserName.'=='.$this->decUserName;
+//            exit;
+            if (!isset($flipParent[$this->decUserName])) {
+                $this->addError($attribute, '为' . $this->insertUserName . '报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
+                return ;
+            }
+            $this->_decId = $decUser['ID'];
+        }
+    }
+
+    /**
+     * 判断指导老师
+     * @param $attribute
+     */
+    public function isConUserName($attribute){
+        if($this->type == self::TYPE_ZC){
+            // 从数据库查看接点会员是否在
+            if(!isset($this->_tempParentUser[$this->conUserName])){
+                $conUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->conUserName]);
+                if(!$conUserTemp){
+                    if($this->insertUserName){
+                        $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'不存在');
+                    } else {
+                        $this->addError($attribute, '指导老师'.$this->conUserName.'不存在');
+                    }
+                    return ;
+                }
+                $conUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($conUserTemp['USER_ID']);
+                $conUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($conUserTemp['USER_ID']);
+                $this->_tempParentUser[$this->conUserName] = [
+                    'USER_NAME' => $this->conUserName,
+                    'ZC_PV' => $conUserTemp['ZC_PV'],
+                    'CON_USER_NAME' => Info::getUserNameByUserId($conUserTemp['CON_UID']),
+                    'REC_USER_NAME' => Info::getUserNameByUserId($conUserTemp['REC_UID']),
+                    'CON_NUM' => $conUserTemp['CON_NUM'],
+                    'REC_NUM' => $conUserTemp['REC_NUM'],
+                    'SYSTEM_ID' => $conUserTemp['SYSTEM_ID'],
+                    'LOCATION' => UserNetwork::getLocation($conUserTemp['USER_ID'], $conUserTemp['CON_UID']),
+                ];
+                // 把该会员下面的5个区是否存在会员都付上
+                for($i=1;$i<=5;$i++){
+                    $this->_tempParentUser[$this->conUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($conUserTemp['USER_ID'], $i);
+                }
+            }
+            $conUser = $this->_tempParentUser[$this->conUserName];
+            // 判断接点会员的下级会员是否大于三个,如果大于三个则不允许
+            if($conUser['CON_NUM'] >= 3){
+                if($this->insertUserName){
+                    $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'下级点位已满');
+                } else {
+                    $this->addError($attribute, '指导老师'.$this->conUserName.'下级点位已满');
+                }
+                return;
+            }
+            if($this->insertUserName){
+                // 把自己加入到临时上级会员数组中
+                $this->_tempParentUser[$this->insertUserName] = [
+                    'USER_NAME' => $this->insertUserName,
+                    //'ZC_PV' => $this->decPv,
+                    'CON_USER_NAME' => $this->conUserName,
+                    'REC_USER_NAME' => $this->recUserName,
+                    'CON_NUM' => 0,
+                    'REC_NUM' => 0,
+                    'SYSTEM_ID' => $conUser['SYSTEM_ID'],
+                    'LOCATION' => $this->location,
+                    'LOCATION1' => 0,
+                    'LOCATION2' => 0,
+                    'LOCATION3' => 0,
+                    'LOCATION4' => 0,
+                    'LOCATION5' => 0,
+                ];
+            }
+
+        }
+    }
+
+    /**
+     * 判断开拓人
+     * @param $attribute
+     */
+    public function isRecUserName($attribute){
+        if($this->type == self::TYPE_ZC){
+            // 开拓人
+            if(!isset($this->_tempParentUser[$this->recUserName])){
+                $recUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->recUserName]);
+                if(!$recUserTemp){
+                    if($this->insertUserName){
+                        $this->addError($attribute, '为'.$this->insertUserName.'报单,开拓人'.$this->recUserName.'不存在');
+                    } else {
+                        $this->addError($attribute, '开拓人'.$this->recUserName.'不存在');
+                    }
+
+                    return ;
+                }
+                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
+                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
+                $this->_tempParentUser[$this->recUserName] = [
+                    'USER_NAME' => $this->recUserName,
+                    'ZC_PV' => $recUserTemp['ZC_PV'],
+                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
+                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
+                    'CON_NUM' => $recUserTemp['CON_NUM'],
+                    'REC_NUM' => $recUserTemp['REC_NUM'],
+                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
+                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
+                ];
+                // 把该会员下面的5个区是否存在会员都付上
+                for($i=1;$i<=5;$i++){
+                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
+                }
+            }
+            $recUser = $this->_tempParentUser[$this->recUserName];
+            $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;
+
+            // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
+            if($this->insertUserName) {
+                $this->loopFindParentToNetwork($this->insertUserName);
+                if (!$this->recUserIsInNetworkParent()) {
+                    $this->addError($attribute, '为' . $this->insertUserName . '报单,开拓人' . $this->recUserName . '不在' . $this->insertUserName . '的安置网上级中');
+                    return ;
+                }
+            }
+
+            // 把自己加入到临时上级会员数组中
+            $this->_tempParentUser[$this->insertUserName] = [
+                'USER_NAME' => $this->insertUserName,
+                //'ZC_PV' => $this->decPv,
+                'CON_USER_NAME' => $this->conUserName,
+                'REC_USER_NAME' => $this->recUserName,
+                'CON_NUM' => 0,
+                'REC_NUM' => 0,
+                'SYSTEM_ID' => $recUser['SYSTEM_ID'],
+                'LOCATION' => $this->location,
+                'LOCATION1' => 0,
+                'LOCATION2' => 0,
+                'LOCATION3' => 0,
+                'LOCATION4' => 0,
+                'LOCATION5' => 0,
+            ];
+        }
+
+    }
+
+    /**
+     * 循环把所有新加入的会员的上级加入到临时变量中
+     * @param null $conUserName
+     * @return bool
+     */
+    private function loopFindParentToNetwork($conUserName = null) {
+        if($conUserName == null ){
+            $conUserName = $this->insertUserName;
+        }
+        $findUserKey = array_search($conUserName, array_column($this->allData, 'insertUserName'));
+        // 如果有这个新加入的会员,则查找其上级接点
+        if($findUserKey !== false){
+            if(strtoupper($this->allData[$findUserKey]['type']) == 'ZC'){
+                $this->_tempNetworkParentUser[$this->insertUserName][] = $this->allData[$findUserKey]['conUserName'];
+                $this->loopFindParentToNetwork($this->allData[$findUserKey]['conUserName']);
+            }
+        }
+        // 如果没有这个新加入的接点,
+        else {
+            if($this->insertUserName == $conUserName){
+                $this->addError('recUserName', '新加入的会员不存在');
+                return false;
+            }
+            // 去数据库里查找这个会员的所有上级
+//            $allParentUser = UserNetwork::find()->select('PUI.USER_NAME')->where('UI.USER_NAME=:USER_NAME', [':USER_NAME'=>$conUserName])->from(UserNetwork::tableName().' AS UN')->join('LEFT JOIN', UserInfo::tableName().' AS UI', 'UN.USER_ID=UI.USER_ID')->join('LEFT JOIN', UserInfo::tableName().' AS PUI', 'UN.PARENT_UID=PUI.USER_ID')->orderBy('PUI.NETWORK_DEEP DESC')->asArray()->all();
+            $baseUser = Info::getBaseUserByUserName($conUserName);
+            $userNetworkInfo = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $baseUser['ID']]);
+            unset($baseUser);
+            $allParentUserIdsArr = explode(',', $userNetworkInfo['PARENT_UIDS']);
+            unset($userNetworkInfo);
+            $allParentUserIds = array_reverse($allParentUserIdsArr);
+            unset($allParentUserIdsArr);
+            if($allParentUserIds){
+                foreach($allParentUserIds as $parentUserId) {
+                    $parentBaseUser = Info::getBaseUserById($parentUserId);
+                    $this->_tempNetworkParentUser[$this->insertUserName][] = $parentBaseUser['USER_NAME'] ;
+
+                    unset($parentUserId, $parentBaseUser);
+                }
+            }
+            unset($allParentUserIds);
+        }
+        return true;
+    }
+
+    /**
+     * 开拓人是否在新加入会员的上级中
+     * @return bool
+     */
+    private function recUserIsInNetworkParent(){
+        return in_array($this->recUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
+    }
+
+    /**
+     * 判断区域是否正确
+     * @param $attribute
+     */
+    public function isLocation($attribute){
+        if($this->type == self::TYPE_ZC){
+            if(!in_array($this->location, [1, 2, 3])){
+                $this->addError($attribute, '市场必须在第1市场、第2市场或第三3市场');
+            }
+            $conUser = $recUser = null;
+            if(isset($this->_tempParentUser[$this->conUserName])){
+                $conUser = $this->_tempParentUser[$this->conUserName];
+            }
+            if(isset($this->_tempParentUser[$this->recUserName])){
+                $recUser = $this->_tempParentUser[$this->recUserName];
+            }
+            if($conUser){
+                // 判断指导老师相应的区位是否已满
+                if($conUser['LOCATION'.$this->location]){
+                    if($this->insertUserName){
+                        $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'的第'.$this->location.'市场已存在会员');
+                    } else {
+                        $this->addError($attribute, '指导老师'.$this->conUserName.'的第'.$this->location.'市场已存在会员');
+                    }
+                    return;
+                }
+                //市场顺序判断
+//                if($conUser['CON_NUM'] == 0 && $this->location != 1){
+//                    if($this->insertUserName){
+//                        $this->addError($attribute, '为'.$this->insertUserName.'报单,市场必须为指导老师'.$this->conUserName.'下第一市场');
+//                    } else {
+//                        $this->addError($attribute, '市场必须为指导老师'.$this->conUserName.'下第一市场');
+//                    }
+//                    return;
+//                }
+//                if($conUser['CON_NUM'] == 1 && $this->location == 3){
+//                    if($this->insertUserName){
+//                        $this->addError($attribute, '为'.$this->insertUserName.'报单,市场必须为指导老师'.$this->conUserName.'第二市场');
+//                    } else {
+//                        $this->addError($attribute, '市场必须为指导老师'.$this->conUserName.'第二市场');
+//                    }
+//                    return;
+//                }
+                $this->_tempParentUser[$this->conUserName]['CON_NUM'] += 1;
+                $this->_tempParentUser[$this->conUserName]['LOCATION'.$this->location] = true;
+            }
+        }
+    }
+
+    /**
+     * 判断会员是否可加入(通过redis结合数据库判断上级会员的情况)
+     * @param $attribute
+     */
+    public function isCanAddUser($attribute){
+        if($this->type == self::TYPE_ZC){
+            // 从数据库查看接点会员是否在
+            if(!isset($this->_tempParentUser[$this->conUserName])){
+                $conUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->conUserName]);
+                if(!$conUserTemp){
+                    $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'不存在');
+                    return ;
+                }
+                $conUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($conUserTemp['USER_ID']);
+                $conUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($conUserTemp['USER_ID']);
+                $this->_tempParentUser[$this->conUserName] = [
+                    'USER_NAME' => $this->conUserName,
+                    //'ZC_PV' => $conUserTemp['ZC_PV'],
+                    'CON_USER_NAME' => Info::getUserNameByUserId($conUserTemp['CON_UID']),
+                    'REC_USER_NAME' => Info::getUserNameByUserId($conUserTemp['REC_UID']),
+                    'CON_NUM' => $conUserTemp['CON_NUM'],
+                    'REC_NUM' => $conUserTemp['REC_NUM'],
+                    'SYSTEM_ID' => $conUserTemp['SYSTEM_ID'],
+                    'LOCATION' => UserNetwork::getLocation($conUserTemp['USER_ID'], $conUserTemp['CON_UID']),
+                ];
+                // 把该会员下面的5个区是否存在会员都付上
+                for($i=1;$i<=5;$i++){
+                    $this->_tempParentUser[$this->conUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($conUserTemp['USER_ID'], $i);
+                }
+            }
+            $conUser = $this->_tempParentUser[$this->conUserName];
+
+            // 开拓人
+            if(!isset($this->_tempParentUser[$this->recUserName])){
+                $recUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->recUserName]);
+                if(!$recUserTemp){
+                    $this->addError($attribute, '为'.$this->insertUserName.'报单,开拓人'.$this->recUserName.'不存在');
+                    return ;
+                }
+                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
+                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
+                $this->_tempParentUser[$this->recUserName] = [
+                    'USER_NAME' => $this->recUserName,
+                    //'ZC_PV' => $recUserTemp['ZC_PV'],
+                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
+                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
+                    'CON_NUM' => $recUserTemp['CON_NUM'],
+                    'REC_NUM' => $recUserTemp['REC_NUM'],
+                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
+                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
+                ];
+                // 把该会员下面的5个区是否存在会员都付上
+                for($i=1;$i<=5;$i++){
+                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
+                }
+            }
+            $recUser = $this->_tempParentUser[$this->recUserName];
+
+            // 判断接点会员的下级会员是否大于三个,如果大于三个则不允许
+            if($conUser['CON_NUM'] >= 3){
+                $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'下级点位已满');
+                return;
+            }
+            // 判断指导老师相应的区位是否已满
+            if($conUser['LOCATION'.$this->location]){
+                $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'该市场已存在会员');
+                return;
+            }
+//            if($conUser['CON_NUM'] == 0 && $this->location != 1){
+//                $this->addError($attribute, '为'.$this->insertUserName.'报单,市场必须为指导老师'.$this->conUserName.'下第一市场');
+//                return;
+//            }
+
+            // 把指导老师的变量的相关数量增加数量
+//            $this->_tempParentUser[$this->conUserName]['CON_NUM'] += 1;
+//            $this->_tempParentUser[$this->conUserName]['LOCATION'.$this->location] = true;
+//            $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;
+
+            // 把自己加入到临时上级会员数组中
+            $this->_tempParentUser[$this->insertUserName] = [
+                'USER_NAME' => $this->insertUserName,
+                //'ZC_PV' => $this->decPv,
+                'CON_USER_NAME' => $this->conUserName,
+                'REC_USER_NAME' => $this->recUserName,
+                'CON_NUM' => 0,
+                'REC_NUM' => 0,
+                'SYSTEM_ID' => $recUser['SYSTEM_ID'],
+                'LOCATION' => $this->location,
+                'LOCATION1' => 0,
+                'LOCATION2' => 0,
+                'LOCATION3' => 0,
+                'LOCATION4' => 0,
+                'LOCATION5' => 0,
+            ];
+        }
+    }
+
+    /**
+     * 报单类型
+     * @param $attribute
+     * @param $params
+     */
+    public function isType($attribute, $params){
+        if(array_key_exists($this->type, $this->_types)){
+            if($this->type == self::TYPE_ZC){
+                if($this->scenario == 'userDec'){
+                    if(!$this->insertUserName) $this->addError($attribute, '首购必须填写加入会员编号');
+                }
+                if(!$this->insertUserName) $this->addError($attribute, '首购必须填写加入会员编号');
+                if(!$this->insertUserIdCard) $this->addError($attribute, '首购必须填写加入会员的身份证号');
+                if(!$this->conUserName) $this->addError($attribute, '首购必须填写加入会员的指导老师编号');
+                if(!$this->recUserName) $this->addError($attribute, '首购必须填写加入会员的开拓人编号');
+                if(!$this->location) $this->addError($attribute, '首购必须填写加入会员的市场');
+            }
+        } else {
+            $this->addError($attribute, '报单类型不正确');
+        }
+    }
+
+    /**
+     * 检验相同身份证 会员是否同一体系内(接点)
+     * @param $attribute
+     */
+    public function isSameSystem($attribute){
+        if(isset($this->_tempParentUser[$this->conUserName])){
+            // 新加入会员的身份证号对应网内的其他会员
+            $otherUser = User::findAllAsArray("ID_CARD=:ID_CARD AND IS_UNION=0 AND DELETED=0 AND (ID_CARD_PREFIX IS NULL OR ID_CARD_PREFIX='')", [':ID_CARD'=>$this->insertUserIdCard]);
+            if(count($otherUser)>=7){
+                $this->addError($attribute, '同一个身份证限制只能报7单');
+            }
+            if($otherUser){
+                $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
+                $isExsit = false;
+                foreach ($otherUser as $conUser){
+                    if(isset($flipParent[$conUser['USER_NAME']])){
+                        $isExsit = true;
+                        break;
+                    }
+                }
+                if (!$isExsit) {
+                    $this->addError($attribute, '为' . $this->insertUserName . '报单,身份证号码相同的会员'.$otherUser[0]['USER_NAME'].'不在' . $this->insertUserName . '的安置网上级中');
+                    return ;
+                }
+            }
+        } else {
+            $this->addError($attribute, '为'.$this->insertUserName.'报单,接点人'.$this->conUserName.'不存在');
+        }
+    }
+
+    /**
+     * 添加报单
+     * @param $allData
+     * @return bool|null
+     * @throws Exception
+     * @throws \yii\db\Exception
+     */
+    public function add($allData){
+        if(!$this->validate()){
+            return null;
+        }
+
+        // 首购单,需要添加会员操作
+        if($this->type == self::TYPE_ZC){
+            if (preg_match("/[\x7f-\xff]/", $this->insertUserName)) {  //判断字符串中是否有中文
+                throw new Exception('会员编号中不能含有汉字');
+            }
+            //报单商品及PV判断
+            $decLevelConfig = Cache::getDecLevelConfig();
+            $decLevel = $decLevelConfig[$this->decLv];
+            $toDecLevel = $this->decLv;
+            if(!$this->decLv){
+                throw new Exception('请选择报单级别');
+            }
+            if($this->decWay==1) {
+                $decPackage = DeclarationPackage::findOneAsArray('ID=:ID', [':ID'=>$this->packageId]);
+                $this->_decAmount = $decPackage['AMOUNT'];
+                $this->_decPv = $decPackage['PV'];
+                $this->_orderGoods[] = [
+                    'GOODS_ID' => $this->packageId,
+                    'PRICE' => $this->_decAmount,
+                    'REAL_PRICE' => $this->_decAmount,
+                    'PV' => $this->_decPv,
+                    'REAL_PV' => $this->_decPv,
+                    'BUY_NUMS' => 1,
+                    'SKU_CODE' => $decPackage['PACKAGE_NO'],
+                    'GOODS_TITLE' => $decPackage['PACKAGE_NAME']
+                ];
+                // 更改库存和状态
+                $data = DeclarationPackage::find()->where(['ID' => $decPackage['ID']])->one();
+                $data->STORE_NUMS = $data->STORE_NUMS - 1;
+                if($data->STORE_NUMS <= 0){
+                    $data->STATUS = 0;
+                    $data->UPDATED_AT = Date::nowTime();
+                }
+                $data->update();
+            }else{
+                $ids = $this->goodsId;
+                $totalAmount = 0;
+                $totalPv = 0;
+                foreach ($this->goodsNum as $k => $v) {
+                    if ($v) {
+                        $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
+                        if (!$goods) {
+                            throw new Exception('商品已下架');
+                            return;
+                        }
+                        if($goods['STORE_NUMS']>0){
+                            $totalAmount += $goods['SELL_PRICE'] * intval($v);
+                            $totalPv += $goods['PRICE_PV'] * intval($v);
+                            $this->_orderGoods[] = [
+                                'GOODS_ID' => $goods['ID'],
+                                'PRICE' => $goods['SELL_PRICE'],
+                                'REAL_PRICE' => $goods['SELL_PRICE'],
+                                'PV' => $goods['PRICE_PV'],
+                                'REAL_PV' => $goods['PRICE_PV'],
+                                'POINT' => $goods['POINT'],
+                                'BUY_NUMS' => intval($v),
+                                'SKU_CODE' => $goods['GOODS_NO'],
+                                'GOODS_TITLE' => $goods['GOODS_NAME']
+                            ];
+                            // 更改库存和状态
+                            $data = ShopGoods::find()->where(['ID' => $goods['ID']])->one();
+                            $data->STORE_NUMS = $data->STORE_NUMS - intval($v);
+                            if($data->STORE_NUMS <= 0){
+                                $data->STATUS = 0;
+                                $data->UPDATED_AT = Date::nowTime();
+                            }
+                            $data->update();
+                        }
+                    }
+                }
+                if($totalPv<$decLevel['PERF']){
+                    throw new Exception('自选商品总PV不能小于所选报单级别PV');
+                }
+                foreach ($decLevelConfig as $key=>$val){
+                    if($totalPv>=$val['PERF']){
+                        $toDecLevel = $key;
+                    }
+                }
+                if($this->decLv!=$toDecLevel){
+                    throw new Exception('自选商品总PV不能超过已选级别下一个级别的PV值');
+                }
+                $this->_decAmount = $totalAmount;
+                $this->_decPv = $totalPv;
+            }
+            //看现金余额是否充足
+            $loginUserId = \Yii::$app->user->id;
+            if (Cash::getAvailableBalance($loginUserId) < $this->_decAmount){
+                throw new Exception('报单人现金不足,无法完成报单');
+            }
+
+            if(!($zcResult = $this->addUser($allData))) {
+                throw new Exception(Form::formatErrorsForApi($this->_userForm->getErrors()));
+            }
+            if(!($decResult = $this->addDecOrder())) {
+                throw new Exception(Form::formatErrorsForApi($decResult->getErrors()));
+            }
+        }
+        return true;
+    }
+
+    /**
+     * 添加会员
+     * @param $allData
+     * @return bool|UserInfo|null
+     * @throws \yii\db\Exception
+     */
+    public function addUser($allData){
+        $period = Period::instance();
+        $userPasswd = $this->password;
+        $userPayPasswd = $this->payPassword;
+        // 如果身份证信息有误,或不足6位,并且没有手动填写密码,就用111111
+        if (Info::simpleIdCardCheck($this->insertUserIdCard)) {
+            if (empty($userPasswd)) {
+                $userPasswd = Info::passwordGenerator($this->insertUserIdCard,$this->insertUserName);
+            }
+            if (empty($userPayPasswd)) {
+                $userPayPasswd = Info::passwordGenerator($this->insertUserIdCard,$this->insertUserName);
+            }
+        } else {
+            if (empty($userPasswd)) {
+                $userPasswd = '111111';
+            }
+            if (empty($userPayPasswd)) {
+                $userPayPasswd = '111111';
+            }
+        }
+
+        // 增加会员
+        $user = new User();
+        $user->USER_NAME = $this->insertUserName;
+        $user->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($userPasswd);
+        $user->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($userPayPasswd);
+        $user->NATION = 0;
+        $user->REAL_NAME = $this->realName;
+        $user->ID_CARD = $this->insertUserIdCard;
+        $user->MOBILE = $this->mobile;
+        $user->ADDRESS = $this->address ? $this->address : '无';
+        $user->OPEN_BANK = $this->openBank;
+        $user->BANK_ADDRESS = $this->bankAddress;
+        $user->BANK_NO = $this->bankNo;
+        $user->BANK_PROVINCE = $this->bankProvince ?? 0;
+        $user->BANK_CITY = $this->bankCity ?? 0;
+        $user->BANK_COUNTY = $this->bankCounty ?? 0;
+        $user->CREATED_AT = Date::nowTime();
+        $user->STATUS = 1;
+        $user->DEC_LV = $this->decLv;
+        $user->LAST_DEC_LV = $this->decLv;
+        $user->EMP_LV = EmployLevel::getDefaultLevelId();
+        $user->PROVINCE = intval($this->province) ?? 0;
+        $user->CITY = intval($this->city) ?? 0;
+        $user->COUNTY = intval($this->county) ?? 0;
+        $user->AVATAR = 'avatar/1.png';
+        $user->IS_DEC = 0;
+        $user->DEC_ID = $this->_decId ?? null;
+        $user->DEC_ROLE_ID = $this->decRoleId ?? null;
+        $user->PERIOD_AT = $period->getNowPeriodNum();
+        $user->IS_DIRECT_SELLER = 0;
+        $user->VERIFIED = 1;
+        $user->VERIFIED_AT = Date::nowTime();
+
+        if (!$user->save()) {
+            throw new Exception(Form::formatErrorsForApi($user->getErrors()));
+        }
+
+        $this->_insertUserId = $user->ID;
+        $userForm = new UserForm();
+        $this->_userForm = $userForm;
+        $userForm->scenario = 'addWithUserName';
+        $userForm->userId = $this->_insertUserId;
+        $userForm->userName = $this->insertUserName;
+        $userForm->zcPv = $this->_decPv;
+        $userForm->zcAmount = $this->_decAmount;
+        $userForm->conUserName = $this->conUserName;
+        $userForm->recUserName = $this->recUserName;
+        $userForm->location = $this->location;
+        $userForm->idCard = $this->insertUserIdCard;
+        $userForm->allData = $allData;
+        if(!$userForm->validate()){
+            $this->addErrors($userForm->getErrors());
+            return false;
+        }
+        if($result = $userForm->add()){
+            return $result;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * 添加报单订单
+     * @return bool|UserInfo|null
+     * @throws \yii\db\Exception
+     */
+    public function addDecOrder(){
+        $periodObj = Period::instance();
+        $nowPeriodNum = $periodObj->getNowPeriodNum();
+        $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
+
+        $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
+        // 加入报单信息
+        $decOrderModel = new DecOrder();
+        $decOrderModel->DEC_SN = 'DS'.$ord;
+        $decOrderModel->ORDER_SN = 'OS'.$ord;
+        $decOrderModel->TYPE = $this->type;
+        $decOrderModel->USER_ID = \Yii::$app->user->id;
+        $decOrderModel->TO_USER_ID = $this->_insertUserId;
+        $decOrderModel->DEC_AMOUNT = $this->_decAmount;
+        $decOrderModel->DEC_PV = $this->_decPv;
+        $decOrderModel->PERIOD_NUM = $nowPeriodNum;
+        $decOrderModel->CALC_MONTH = $nowCalcMonth;
+        $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        $decOrderModel->PAID_WALLET = 'cash';
+        $decOrderModel->CON_USER_ID = Info::getUserIdByUserName($this->conUserName);
+        $decOrderModel->REC_USER_ID = Info::getUserIdByUserName($this->recUserName);
+        $decOrderModel->DEC_ID = $this->_decId;
+        $decOrderModel->IS_DEL = 0;
+        $decOrderModel->CREATED_AT = Date::nowTime();
+        if(!$decOrderModel->save()){
+            throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
+        }
+
+        // 加入订单信息
+        $warehouse = Region::getWarehouseByCode($this->province);//仓库
+        if(!$warehouse){
+            throw new Exception('地区暂时不支持配送,具体联系客服');
+        }
+        $orderModel = new Order();
+        $orderModel->SN = 'OS'.$ord;
+        $orderModel->DEC_SN = 'DS'.$ord;
+        $orderModel->ORDER_TYPE = $this->type;
+        $orderModel->USER_ID = $this->_insertUserId;
+        $orderModel->USER_NAME = $this->insertUserName;
+        $orderModel->ORDER_AMOUNT = $this->_decAmount;
+        $orderModel->PV = $this->_decPv;
+        $orderModel->PAY_AMOUNT = $this->_decAmount;
+        $orderModel->PAY_PV = $this->_decPv;
+        $orderModel->PAY_AT = Date::nowTime();
+        $orderModel->PAY_TYPE = 'cash';
+        $orderModel->PERIOD_NUM = $nowPeriodNum;
+        $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        $orderModel->FREIGHT = 0;
+        $orderModel->PAY_FREIGHT = 0;
+        $orderModel->CONSIGNEE = $this->consignee;
+        $orderModel->MOBILE = $this->acceptMobile;
+        $orderModel->PROVINCE = $this->province;
+        $orderModel->CITY = $this->city;
+        $orderModel->COUNTY = intval($this->county) ?? 0;
+        $orderModel->ADDRESS = $this->address;
+        $orderModel->WAREHOUSE = $warehouse;
+        $orderModel->STATUS = 1;
+        $orderModel->CREATED_AT = Date::nowTime();
+        $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
+        if(!$orderModel->save()){
+            throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
+        }
+        // 加入商品到订单商品表
+        foreach($this->_orderGoods as $key=>$value){
+            $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
+            $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        }
+        OrderGoods::batchInsert($this->_orderGoods);
+
+        //写入收货地址信息
+        $addressModel = new ReceiveAddress();
+        $addressModel->USER_ID = $this->_insertUserId;
+        $addressModel->USER_NAME = $this->insertUserName;
+        $addressModel->CONSIGNEE = $this->consignee;
+        $addressModel->MOBILE = $this->acceptMobile;
+        $addressModel->PROVINCE = $this->province;
+        $addressModel->CITY = $this->city;
+        $addressModel->COUNTY = intval($this->county) ?? 0;
+        $addressModel->ADDRESS = $this->address;
+        $addressModel->IS_DEFAULT = 1;
+        if(!$addressModel->save()){
+            throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
+        }
+        //扣报单人现金钱包
+        Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'报单', 'ORDER_SN' => $orderModel->SN]);
+
+        return $addressModel;
+    }
+
+
+
+    /**
+     * 删单
+     * @return bool
+     * @throws \yii\db\Exception
+     */
+    public function delete(){
+        if(!$this->validate()){
+            return false;
+        }
+        $transaction = \Yii::$app->db->beginTransaction();
+        try {
+            $oneOrder = $this->_oneOrder;
+            // 首购单要删除会员
+            if($this->type == self::TYPE_ZC){
+                UserInfo::deleteUser($oneOrder['TO_USER_ID']);
+            }
+            // 如果是复销单的话,还需要考虑给会员的复销池减去金额
+            elseif($this->type == self::TYPE_FX){
+                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
+            }
+            $transaction->commit();
+        } catch (Exception $e) {
+            $transaction->rollBack();
+            $this->addError('delete', $e->getMessage());
+            return false;
+        }
+        return true;
+    }
+
+}

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

@@ -209,7 +209,7 @@ class DeclarationUpgradeForm extends Model
         if(!$warehouse){
             throw new Exception('地区暂时不支持配送,具体联系客服');
         }
-        
+
         $upgradeType = $isObserve ? 1 : 2; // 1补差  2全额
         $periodObj = Period::instance();
         $nowPeriodNum = $periodObj->getNowPeriodNum();
@@ -329,7 +329,7 @@ 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' =>'为'.$this->insertUserName.'升级报单', 'ORDER_SN' => $orderModel->SN]);
             // 为被升级人进行升级操作
             $decLevelLog = new DecLevelLog();
             $decLog = [
@@ -401,7 +401,7 @@ class DeclarationUpgradeForm extends Model
     public function alreadyMaxDec($attribute) {
         $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
         $userDecId = $baseInfo['DEC_LV'];// 用户当前的级别
-        $maxPerfInfo = DeclarationLevel::getMaxDecPref(); 
+        $maxPerfInfo = DeclarationLevel::getMaxDecPref();
         $maxDecId = $maxPerfInfo['ID']; // 级别配置中最高级别ID
         if ($maxDecId == $userDecId) {
             $this->addError($attribute, '已是最高级别,无需升级');
@@ -436,7 +436,7 @@ class DeclarationUpgradeForm extends Model
             }
         }
         unset($allParentUserIds);
-        
+
         return true;
     }
 

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

@@ -106,11 +106,11 @@ class OrderDeleteForm extends Model
                 ->where("ORDER_SN=:ORDER_SN", [':ORDER_SN' => $sn])
                 ->asArray()
                 ->one();
-                $userId = $decInfo['USER_ID']; 
+                $userId = $decInfo['USER_ID'];
                 // 删除报单
                 $delDecOrder = DecOrder::updateAll(
-                    ['IS_DEL'=>1, 'DELETED_AT'=>Date::nowTime()], 
-                    'ORDER_SN=:ORDER_SN', 
+                    ['IS_DEL'=>1, 'DELETED_AT'=>Date::nowTime()],
+                    'ORDER_SN=:ORDER_SN',
                     ['ORDER_SN'=>$sn]
                 );
                 if (!$delDecOrder) {
@@ -138,18 +138,18 @@ class OrderDeleteForm extends Model
                     }
                     $isLock = 1;
                 }
-            } 
+            }
             // 公共的退钱,删除订单操作
             $delOrder = Order::updateAll(
-                ['IS_DELETE'=>1, 'DELETED_AT'=>Date::nowTime()], 
-                'SN=:SN', 
+                ['IS_DELETE'=>1, 'DELETED_AT'=>Date::nowTime()],
+                'SN=:SN',
                 ['SN'=>$sn]
             );
             if (!$delOrder) {
                 $transaction->rollBack();
                 throw new Exception('删除订单失败');
             }
-            
+
             // 记录退还前的账户原资金
             $cash = $point = $bonus = $exchange = 0;
             $userBonus = UserBonus::findUseSlaves()
@@ -172,11 +172,11 @@ class OrderDeleteForm extends Model
             //退还
             $amountResult = false;
             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) {
                 $transaction->rollBack();
@@ -226,7 +226,7 @@ class OrderDeleteForm extends Model
                 $this->addErrors($returnOrderModel->getErrors());
                 return false;
             }
-            
+
             $transaction->commit();
         } catch(Exception $e) {
             $transaction->rollBack();
@@ -317,8 +317,8 @@ class OrderDeleteForm extends Model
                     $this->addError($attribute, '此注册报单,存在复消单,无法删除,订单编号为:'.$this->orderSn);
                     return ;
                 }
-            }   
+            }
         }
-        return true; 
+        return true;
     }
 }

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

@@ -484,11 +484,11 @@ class OrderForm extends Model
 
         //扣除会员余额/积分
         if($this->payType=='cash') {
-            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
+            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付', '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{
-            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]);
         }
         return $orderModel;
     }
@@ -669,9 +669,9 @@ class OrderForm extends Model
 
         //扣除会员余额/积分
         if($this->payType=='cash') {
-            Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
+            Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付', 'ORDER_SN' => $orderModel->SN]);
         }else{
-            Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销点数兑换']);
+            Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销点数兑换', 'ORDER_SN' => $orderModel->SN]);
         }
         return $orderModel;
     }

+ 27 - 1
common/models/forms/OrderPeriodAdjustForm.php

@@ -7,9 +7,14 @@ 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\FlowReconsumePoints;
+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
@@ -101,13 +106,34 @@ class OrderPeriodAdjustForm extends Model
         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 'point':
+                    FlowReconsumePoints::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;
+                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);