kevin_zhangl 3 лет назад
Родитель
Сommit
5e3b2ebbc1

+ 94 - 0
common/models/ApproachDecOrder.php

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

+ 2 - 0
common/models/ApproachOrder.php

@@ -48,6 +48,8 @@ use Yii;
  * @property int $WAREHOUSE 发货仓
  * @property string $EMAIL 邮箱
  * @property string $NOTE 备注说明
+ * @property string $LGA_NAME LGA_NAME
+ * @property string $CITY_NAME 城市
  */
 class ApproachOrder extends \common\components\ActiveRecord
 {

+ 910 - 0
common/models/forms/ApproachDeclarationForm.php

@@ -0,0 +1,910 @@
+<?php
+namespace common\models\forms;
+
+use common\components\Model;
+use common\helpers\Cache;
+use common\helpers\Date;
+use common\helpers\Form;
+use common\helpers\LoggerTool;
+use common\helpers\user\Cash;
+use common\helpers\user\Reconsume;
+use common\helpers\user\Info;
+use common\models\ApproachDecOrder;
+use common\models\ApproachOrder;
+use common\models\ApproachOrderGoods;
+use common\models\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 ApproachDeclarationForm extends Model
+{
+    public $type;
+    public $decLv;
+    public $decWay;
+    public $packageId;
+    public $goodsId;
+    public $goodsNum;
+    public $insertUserName;
+    public $password;
+    public $payPassword;
+    public $realName;
+    public $insertUserIdCard;
+    public $mobile;
+    public $email;
+    public $address;
+    public $openBank;
+    public $bankAddress;
+    public $bankNo;
+    public $bankProvince;
+    public $bankCity;
+    public $bankCounty;
+    public $conUserName;
+    public $recUserName;
+    public $decUserName;
+    public $location;
+    public $consignee;
+    public $acceptMobile;
+    public $province;
+    public $city;
+    public $county;
+    public $cityName;
+    public $lgaName;
+    public $payType;
+
+    // 传过来的全部数据
+    public $allData;
+    private $_decId;
+    public $_insertUserId;
+    private $_decAmount;
+    private $_decPv;
+    private $_orderGoods;
+
+    // 批量报单时添加会员的REDIS里面缓存的添加的会员资料
+    const REDIS_WAIT_ADD_USER = 'user:dec:waitAdd';
+
+    const TYPE_ZC = 'ZC';
+//    const TYPE_YH = 'YH';
+    const TYPE_ZG = 'ZG';
+    const TYPE_LS = 'LS';
+    const TYPE_FX = 'FX';
+
+//    private $_modelClass = null;
+    private $_oneOrder = null;
+    private $_userForm = null;
+    // 全部的上级(安置网和开拓网)
+    private $_tempParentUser = [];
+    // 全部的安置网上级
+    private $_tempNetworkParentUser = [];
+    // 全部的开拓网上级
+    private $_tempRelationParentUser = [];
+    private $_types = [
+        self::TYPE_ZC => [
+            'name' => '首购单',
+        ],
+//        self::TYPE_YH => [
+//            'class' => DeclarationYH::class,
+//            'table' => '{{%DECLARATION_YH}}',
+//            'name' => '优惠单',
+//        ],
+        self::TYPE_ZG => [
+            'name' => '升级增购单',
+        ],
+        self::TYPE_LS => [
+            'name' => '零售单',
+        ],
+        self::TYPE_FX => [
+            'name' => '复销单',
+        ],
+    ];
+
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['type','decLv','decWay','packageId', 'insertUserName', 'realName',/* 'insertUserIdCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo','bankProvince','bankCity','bankCounty','consignee','acceptMobile','province','city','county','cityName','lgaName','decUserName', 'conUserName', 'recUserName', 'location'], 'trim'],
+            [['type','decLv','decWay','insertUserName',/* 'insertUserIdCard',*/'password','payPassword','decUserName'], 'required'],
+            [['type'], 'isType', 'on'=>['userDec', 'canDec']],
+            [['insertUserName'], 'isCanAddUser'],
+            [['decUserName'], 'issetDec'],
+            [['conUserName'], 'isConUserName'],
+            [['recUserName'], 'isRecUserName'],
+            [['location'], 'isLocation'],
+//            [['insertUserIdCard'], 'isSameSystem'],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'type' => 'Entry type',//报单类型
+            'decLv' => 'Entry level',//报单级别
+            //'decPv' => '报单PV',
+            'decWay' => 'Entry method',//报单方式
+            'packageId' => 'Entry Package',//报单套餐
+            'goodsId' => 'product ID',//商品ID
+            'goodsNum' => 'Product quantity',//商品数量
+            //'addType' => '新增会员方式',
+            'insertUserName' => 'Member user name',//会员用户名
+            'password' => 'Login password',//登陆密码
+            'payPassword' => 'Payment password',//支付密码
+            'realName' => 'Member name',//会员姓名
+            'insertUserIdCard' => 'ID',//身份证号
+            'mobile' => 'phone number',//手机号
+            'openBank' => 'openBank',//开户行
+            'bankAddress' => 'bankAddress',//开户支行
+            'bankNo' => 'bankNo',//银行账号
+            'bankProvince' => 'bankProvince',//银行省份
+            'bankCity' => 'bankCity',//银行城市
+            'bankCounty' => 'bankCounty',//银行县区
+            'conUserName' => 'Instructor user name',//指导老师用户名
+            'recUserName' => 'Developer user name',//开拓人用户名
+            'decUserName' => 'Entry center user name',//报单中心用户名
+            'conUid' => 'Instructor member ID',//指导老师会员ID
+            'recUid' => 'Pioneer member ID',//'开拓人会员ID
+            'location' => 'market',//市场
+            'consignee' => 'consignee',//收货人
+            'acceptMobile' => 'Consignee is phone number',//收货人手机
+            'province' => 'Receiving Province',//收货省
+            'city' => 'Receiving City',//收货市
+            'county' => 'Receiving area / county',//收货区县
+            'address' => 'Receiving detailed address',//收货详细地址
+        ];
+    }
+
+    /**
+     * 指定场景
+     * @return array
+     */
+    public function scenarios()
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            'userDec' => ['type','allData', 'decLv','decWay','insertUserName','password','payPassword', 'realName',/* 'insertUserIdCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankProvince','bankCity','bankCounty', 'consignee','acceptMobile','province',/*'city','county',*/ 'conUserName', 'recUserName','decUserName', 'location', 'email'],
+            'canDec' => ['type', 'insertUserName',/* 'insertUserIdCard',*/ 'conUserName', 'recUserName', 'location'],
+            '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, 'Entry center does not exist');//报单中心不存在
+            return false;
+        } else {
+            // 判断报单中心是否在新加入会员的安置网上级中
+            $this->loopFindParentToNetwork($this->insertUserName);
+            //反转数组,in_array搜索错误
+            //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
+            $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
+//            var_dump($flipParent);
+//            echo $this->insertUserName.'=='.$this->decUserName;
+//            exit;
+            if (!isset($flipParent[$this->decUserName])) {
+                //$this->addError($attribute, '为' . $this->insertUserName . '报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
+                $this->addError($attribute, 'To' . $this->insertUserName . 'Entry,Entry Center' . $this->decUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
+                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.'不存在');
+                        $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Instructor'.$this->conUserName.'not in exist');
+                    } else {
+                        //$this->addError($attribute, '指导老师'.$this->conUserName.'不存在');
+                        $this->addError($attribute, 'Instructor'.$this->conUserName.'not in exist');
+                    }
+                    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.'下级点位已满');
+                    $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Instructor'.$this->conUserName.'lower level is full');
+                } else {
+                    //$this->addError($attribute, '指导老师'.$this->conUserName.'下级点位已满');
+                    $this->addError($attribute, 'Instructor'.$this->conUserName.'lower level is full');
+                }
+                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.'不存在');
+                        $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Pioneer'.$this->recUserName.'not in exist');
+                    } else {
+                       // $this->addError($attribute, '开拓人'.$this->recUserName.'不存在');
+                        $this->addError($attribute, 'Pioneer'.$this->recUserName.'not in exist');
+                    }
+
+                    return ;
+                }
+                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
+                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
+                $this->_tempParentUser[$this->recUserName] = [
+                    'USER_NAME' => $this->recUserName,
+                    'ZC_PV' => $recUserTemp['ZC_PV'],
+                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
+                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
+                    'CON_NUM' => $recUserTemp['CON_NUM'],
+                    'REC_NUM' => $recUserTemp['REC_NUM'],
+                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
+                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
+                ];
+                // 把该会员下面的5个区是否存在会员都付上
+                for($i=1;$i<=5;$i++){
+                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
+                }
+            }
+            $recUser = $this->_tempParentUser[$this->recUserName];
+            $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;
+
+            // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
+            if($this->insertUserName) {
+                $this->loopFindParentToNetwork($this->insertUserName);
+                if (!$this->recUserIsInNetworkParent()) {
+                   // $this->addError($attribute, '为' . $this->insertUserName . '报单,开拓人' . $this->recUserName . '不在' . $this->insertUserName . '的安置网上级中');
+                    $this->addError($attribute, 'To' . $this->insertUserName . 'Entry,Pioneer' . $this->recUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
+                    return ;
+                }
+            }
+
+            // 把自己加入到临时上级会员数组中
+            $this->_tempParentUser[$this->insertUserName] = [
+                'USER_NAME' => $this->insertUserName,
+                //'ZC_PV' => $this->decPv,
+                'CON_USER_NAME' => $this->conUserName,
+                'REC_USER_NAME' => $this->recUserName,
+                'CON_NUM' => 0,
+                'REC_NUM' => 0,
+                'SYSTEM_ID' => $recUser['SYSTEM_ID'],
+                'LOCATION' => $this->location,
+                'LOCATION1' => 0,
+                'LOCATION2' => 0,
+                'LOCATION3' => 0,
+                'LOCATION4' => 0,
+                'LOCATION5' => 0,
+            ];
+        }
+
+    }
+
+    /**
+     * 循环把所有新加入的会员的上级加入到临时变量中
+     * @param 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', '新加入的会员不存在');
+                $this->addError('recUserName', 'New member does not exist');
+                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 AND PARENT_UIDS <> ""', [':USER_ID' => $baseUser['ID']]);
+            unset($baseUser);
+            if ($userNetworkInfo) {
+                $allParentUserIdsArr = explode(',', $userNetworkInfo['PARENT_UIDS']);
+                unset($userNetworkInfo);
+                $allParentUserIds = array_reverse($allParentUserIdsArr);
+                unset($allParentUserIdsArr);
+                if($allParentUserIds && count($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市场');
+                $this->addError($attribute, 'Please select a market');
+            }
+            $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.'市场已存在会员');
+                        $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Instructor'.$this->conUserName.'the'.($this->location == 1 ? 'left' : 'regiht').' superior already existing member');
+                    } else {
+                       // $this->addError($attribute, '指导老师'.$this->conUserName.'的第'.$this->location.'市场已存在会员');
+                        $this->addError($attribute, 'Instructor'.$this->conUserName.'the'.($this->location == 1 ? 'left' : 'regiht').'superior already existing member');
+                    }
+                    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.'不存在');
+                    $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Instructor'.$this->conUserName.'not in exist');
+                    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.'不存在');
+                    $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Pioneer'.$this->recUserName.'not in exist');
+                    return ;
+                }
+                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
+                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
+                $this->_tempParentUser[$this->recUserName] = [
+                    'USER_NAME' => $this->recUserName,
+                    //'ZC_PV' => $recUserTemp['ZC_PV'],
+                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
+                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
+                    'CON_NUM' => $recUserTemp['CON_NUM'],
+                    'REC_NUM' => $recUserTemp['REC_NUM'],
+                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
+                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
+                ];
+                // 把该会员下面的5个区是否存在会员都付上
+                for($i=1;$i<=5;$i++){
+                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
+                }
+            }
+            $recUser = $this->_tempParentUser[$this->recUserName];
+
+            // 判断接点会员的下级会员是否大于三个,如果大于三个则不允许
+            if($conUser['CON_NUM'] >= 3){
+//                $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'下级点位已满');
+                $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Pioneer'.$this->conUserName.'lower level is full');
+                return;
+            }
+            // 判断指导老师相应的区位是否已满
+            if($conUser['LOCATION'.$this->location]){
+//                $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'该市场已存在会员');
+                $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Pioneer'.$this->conUserName.'Members already exist in this market');
+                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, 'Membership number must be filled in for initial purchase');//首购必须填写加入会员编号
+                }
+                if(!$this->insertUserName) $this->addError($attribute, 'Membership number must be filled in for initial purchase');//首购必须填写加入会员编号
+//                if(!$this->insertUserIdCard) $this->addError($attribute, 'For the first purchase, the ID number of the member must be filled in');//首购必须填写加入会员的身份证号
+                if(!$this->conUserName) $this->addError($attribute, 'For the first purchase, you must fill in the instructor number of the member');//首购必须填写加入会员的指导老师编号
+                if(!$this->recUserName) $this->addError($attribute, 'For the first purchase, the pioneer number of the member must be filled in');//首购必须填写加入会员的开拓人编号
+                if(!$this->location) $this->addError($attribute, 'The first purchase must be filled in the market of the member');//首购必须填写加入会员的市场
+            }
+        } else {
+            $this->addError($attribute, 'Incorrect entry type');//报单类型不正确
+        }
+    }
+
+    /**
+     * 检验相同身份证 会员是否同一体系内(接点)
+     * @param $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, 'Only 7 documents can be reported for the same ID card');//同一个身份证限制只能报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 . '的安置网上级中');
+//                    $this->addError($attribute, 'To' . $this->insertUserName . 'Entry,Members with the same ID number'.$otherUser[0]['USER_NAME'].'not in exist' . $this->insertUserName . 'in the placement superiors');
+//                    return ;
+//                }
+//            }
+//        } else {
+////            $this->addError($attribute, '为'.$this->insertUserName.'报单,接点人'.$this->conUserName.'不存在');
+//            $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Contact person'.$this->conUserName.'not in exist');
+//        }
+//    }
+
+    /**
+     * 添加报单
+     * @param $allData
+     * @return ApproachOrder
+     * @throws Exception
+     * @throws \yii\db\Exception
+     */
+    public function add($allData){
+        if(!$this->validate()){
+            return null;
+        }
+
+        // 首购单,需要添加会员操作
+        if($this->type == self::TYPE_ZC) {
+            try {
+                if (preg_match("/[\x7f-\xff]/", $this->insertUserName)) {  //判断字符串中是否有中文
+                    throw new Exception('Member number cannot contain Chinese characters');//会员编号中不能含有汉字
+                }
+                //报单商品及PV判断
+                $decLevelConfig = Cache::getDecLevelConfig();
+                $decLevel = $decLevelConfig[$this->decLv];
+                $toDecLevel = $this->decLv;
+                if (!$this->decLv) {
+                    throw new Exception('Please select the entry level');//请选择报单级别
+                }
+
+                if ($this->decWay == 1) {
+                    $decPackage = DeclarationPackage::findOneAsArray('ID=:ID', [':ID' => $this->packageId]);
+                    $this->_decAmount = $decPackage['AMOUNT'];
+                    $this->_decPv = $decPackage['PV'];
+                    $this->_orderGoods[] = [
+                        'GOODS_ID' => $this->packageId,
+                        'PRICE' => $this->_decAmount,
+                        'REAL_PRICE' => $this->_decAmount,
+                        'PV' => $this->_decPv,
+                        'REAL_PV' => $this->_decPv,
+                        'BUY_NUMS' => 1,
+                        'SKU_CODE' => $decPackage['PACKAGE_NO'],
+                        'GOODS_TITLE' => $decPackage['PACKAGE_NAME'],
+                        'EMAIL' => $this->email
+                    ];
+                } else {
+                    $ids = $this->goodsId;
+                    $totalAmount = 0;
+                    $totalPv = 0;
+                    foreach ($this->goodsNum as $k => $v) {
+                        if ($v) {
+                            $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID' => $ids[$k]]);
+                            if ($goods['STORE_NUMS'] > 0) {
+                                $totalAmount += $goods['SELL_PRICE'] * intval($v);
+                                $totalPv += $goods['PRICE_PV'] * intval($v);
+                                $this->_orderGoods[] = [
+                                    'GOODS_ID' => $goods['ID'],
+                                    'PRICE' => $goods['SELL_PRICE'],
+                                    'REAL_PRICE' => $goods['SELL_PRICE'],
+                                    'PV' => $goods['PRICE_PV'],
+                                    'REAL_PV' => $goods['PRICE_PV'],
+                                    'POINT' => $goods['POINT'],
+                                    'BUY_NUMS' => intval($v),
+                                    'SKU_CODE' => $goods['GOODS_NO'],
+                                    'GOODS_TITLE' => $goods['GOODS_NAME'],
+                                    'EMAIL' => $this->email,
+                                    'TAX_RATE' => $goods['TAX_RATE'],
+                                ];
+                            }
+                        }
+                    }
+                    if ($totalPv < $decLevel['PERF']) {
+                        throw new Exception('The total BV of self selected goods cannot be less than the BV of the selected entry level');//自选商品总BV不能小于所选报单级别BV
+                    }
+                    foreach ($decLevelConfig as $key => $val) {
+                        if ($totalPv >= $val['PERF']) {
+                            $toDecLevel = $key;
+                        }
+                    }
+                    if ($this->decLv != $toDecLevel) {
+                        throw new Exception('The total BV of self selected goods cannot exceed the BV value of the next level under the selected level');//自选商品总BV不能超过已选级别下一个级别的BV值
+                    }
+                    $this->_decAmount = $totalAmount;
+                    $this->_decPv = $totalPv;
+                }
+
+                if (!($this->addUser($allData))) {
+                    throw new Exception(Form::formatErrorsForApi($this->_userForm->getErrors()));
+                }
+
+                $decResult = $this->addDecOrder();
+                if (!$decResult) {
+                    throw new Exception(Form::formatErrorsForApi($decResult->getErrors()));
+                }
+
+                return $decResult;
+            } catch (\Exception $e) {
+                throw new Exception(Form::formatErrorsForApi($e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage()));
+            }
+        }
+        return true;
+    }
+
+    /**
+     * 添加会员
+     * @param $allData
+     * @return bool|UserInfo|null
+     * @throws \yii\db\Exception
+     */
+    public function addUser($allData){
+        $period = Period::instance();
+        // 增加会员
+        $user = new User();
+        $user->USER_NAME = $this->insertUserName;
+        $user->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
+        $user->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($this->payPassword);
+        $user->NATION = 0;
+        $user->REAL_NAME = $this->realName;
+        $user->ID_CARD = $this->mobile;
+        $user->MOBILE = $this->mobile;
+        $user->EMAIL = $this->email;
+        $user->ADDRESS = $this->address ? $this->address : 'nothing';//无
+        $user->OPEN_BANK = $this->openBank;
+        $user->BANK_ADDRESS = $this->bankAddress;
+        $user->BANK_NO = $this->bankNo;
+        $user->BANK_PROVINCE = $this->bankProvince ?? 0;
+        $user->BANK_CITY = $this->bankCity ?? 0;
+        $user->BANK_COUNTY = $this->bankCounty ?? 0;
+        $user->CREATED_AT = Date::nowTime();
+        $user->STATUS = 1;
+        $user->DEC_LV = $this->decLv;
+        $user->LAST_DEC_LV = $this->decLv;
+        $user->EMP_LV = EmployLevel::getDefaultLevelId();
+        $user->PROVINCE = $this->province ?? 0;
+        $user->LGA_NAME = $this->lgaName;
+        $user->CITY_NAME = $this->cityName;
+//        $user->CITY = $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->mobile;
+        $userForm->allData = $allData;
+        if(!$userForm->validate()){
+            $this->addErrors($userForm->getErrors());
+            return false;
+        }
+        if($result = $userForm->add()){
+            return $result;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * 添加报单订单
+     * @throws \yii\db\Exception
+     */
+    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 ApproachDecOrder();
+        $decOrderModel->DEC_SN = 'DS' . $ord;
+        $decOrderModel->ORDER_SN = 'OS' . $ord;
+        $decOrderModel->TYPE = $this->type;
+        $decOrderModel->USER_ID = \Yii::$app->user->id;
+        $decOrderModel->TO_USER_ID = $this->_insertUserId;
+        $decOrderModel->DEC_AMOUNT = $this->_decAmount;
+        $decOrderModel->DEC_PV = $this->_decPv;
+        $decOrderModel->PERIOD_NUM = $nowPeriodNum;
+        $decOrderModel->CALC_MONTH = $nowCalcMonth;
+        $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        $decOrderModel->PAID_WALLET = $this->payType;
+        $decOrderModel->CON_USER_ID = Info::getUserIdByUserName($this->conUserName);
+        $decOrderModel->REC_USER_ID = Info::getUserIdByUserName($this->recUserName);
+        $decOrderModel->DEC_ID = $this->_decId;
+        $decOrderModel->IS_DEL = 0;
+        $decOrderModel->CREATED_AT = Date::nowTime();
+        $decOrderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
+        if(!$decOrderModel->save()){
+            throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
+        }
+
+        // 加入订单信息
+        if ($this->province!=1) {
+            // 仓库
+            $warehouse = Region::getWarehouseByCode($this->province);
+            if (!$warehouse) {
+                // 地区暂时不支持配送,具体联系客服
+                throw new Exception('Delivery is temporarily not supported in the region. Contact customer service for details');
+            }
+        } else {
+            $warehouse = '01';
+        }
+
+        $orderModel = new ApproachOrder();
+        $orderModel->SN = 'OS' . $ord;
+        $orderModel->DEC_SN = 'DS' . $ord;
+        $orderModel->ORDER_TYPE = $this->type;
+        $orderModel->USER_ID = $this->_insertUserId;
+        $orderModel->USER_NAME = $this->insertUserName;
+        $orderModel->ORDER_AMOUNT = $this->_decAmount;
+        $orderModel->PV = $this->_decPv;
+        $orderModel->PAY_AMOUNT = $this->_decAmount;
+        $orderModel->PAY_PV = $this->_decPv;
+        $orderModel->PAY_AT = 0;
+        $orderModel->PAY_TYPE = $this->payType;
+        $orderModel->PERIOD_NUM = $nowPeriodNum;
+        $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        $orderModel->FREIGHT = 0;
+        $orderModel->PAY_FREIGHT = 0;
+        $orderModel->CONSIGNEE = $this->consignee;
+        $orderModel->MOBILE = $this->acceptMobile;
+        $orderModel->EMAIL = $this->email ?: $this->insertUserName . '@elken.net';
+        $orderModel->PROVINCE = $this->province;
+        $orderModel->LGA_NAME = $this->lgaName;
+        $orderModel->CITY_NAME = $this->cityName;
+        $orderModel->ADDRESS = $this->address;
+        $orderModel->WAREHOUSE = $warehouse;
+        $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
+        $orderModel->CREATED_AT = Date::nowTime();
+        $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
+        if ($this->province==1) {
+            $orderModel->EXPRESS_TYPE = 1;
+        }
+        if (!$orderModel->save()) {
+            throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
+        }
+
+        // 加入商品到订单商品表
+        foreach($this->_orderGoods as $key=>$value){
+            $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
+            $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        }
+        ApproachOrderGoods::batchInsert($this->_orderGoods);
+
+        // 写入收货地址信息,判断province字段,当不为1时,插入收货地址信息
+        $addressModel = new ReceiveAddress();
+        if ($this->province != 1) {
+            $addressModel->USER_ID = $this->_insertUserId;
+            $addressModel->USER_NAME = $this->insertUserName;
+            $addressModel->CONSIGNEE = $this->consignee;
+            $addressModel->MOBILE = $this->acceptMobile;
+            $addressModel->PROVINCE = $this->province;
+            $addressModel->CITY_NAME = $this->cityName;
+            $addressModel->LGA_NAME = $this->lgaName;
+            $addressModel->ADDRESS = $this->address;
+            $addressModel->IS_DEFAULT = 1;
+            if (!$addressModel->save()) {
+                throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
+            }
+        }
+
+        return $orderModel;
+    }
+
+
+
+    /**
+     * 删单
+     * @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]);
+                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'Deletion deduction', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
+            }
+            $transaction->commit();
+        } catch (Exception $e) {
+            $transaction->rollBack();
+            $this->addError('delete', $e->getMessage());
+            return false;
+        }
+        return true;
+    }
+
+}

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

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

+ 17 - 2
common/models/forms/ApproachOrderForm.php

@@ -11,9 +11,11 @@ use common\helpers\user\Balance;
 use common\helpers\user\Cash;
 use common\helpers\user\Info;
 use common\libs\logging\operate\AdminOperate;
+use common\models\ApproachDecOrder;
 use common\models\ApproachOrder;
 use common\models\ApproachOrderGoods;
 use common\models\DealType;
+use common\models\DecOrder;
 use common\models\Order;
 use common\models\OrderGoods;
 use common\models\Period;
@@ -316,6 +318,19 @@ class ApproachOrderForm extends Model
                 $approachOrderGood['EMAIL'] = $this->email;
             }
             OrderGoods::batchInsert($approachOrderGoods);
+            // 同步报单
+            $approachDecOrder = ApproachDecOrder::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+            if ($approachDecOrder) {
+                foreach ($approachDecOrder as $decOrder) {
+                    unset($decOrder['STATUS']);
+                }
+                DecOrder::batchInsert($approachDecOrder);
+            }
+
+            // 删除中间表
+            ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
+            ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+            ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
 
             $transaction->commit();
         } catch (Exception $e) {
@@ -378,9 +393,9 @@ class ApproachOrderForm extends Model
 
         // 汇率
         $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
-        // 运费.美元转奈拉
+        // 运费.奈拉
         $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
-        // 普通商品免运费阈值.美元转奈拉
+        // 普通商品免运费阈值.奈拉
         $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
 
         $this->_decAmount = $totalAmount;

+ 5 - 1
frontendApi/modules/v1/controllers/ShopController.php

@@ -15,6 +15,7 @@ use common\helpers\Form;
 use common\helpers\LoggerTool;
 use common\helpers\Tool;
 use common\helpers\user\Info;
+use common\models\ApproachDecOrder;
 use common\models\ApproachOrder;
 use common\models\ApproachOrderGoods;
 use common\models\DealType;
@@ -229,7 +230,6 @@ class ShopController extends BaseController {
 
             if ($formModel->load($load, '') && $order = $formModel->verifyPayStack()) {
                 LoggerTool::error($order);
-//                return static::notice($order);
                 return http_response_code(200);
             } else {
                 LoggerTool::error(Form::formatErrorsForApi($formModel->getErrors()));
@@ -246,8 +246,12 @@ class ShopController extends BaseController {
     public function actionDeleteApproachOrder()
     {
         $orderSn = \Yii::$app->request->post('orderSn');
+        // 删除订单中间表
         ApproachOrder::deleteAll('SN = :SN', [':SN' => $orderSn]);
+        // 删除订单商品中间表
         ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $orderSn]);
+        // 删除报单中间表
+        ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $orderSn]);
 
         return static::notice('');
     }

+ 21 - 9
frontendApi/modules/v1/controllers/UserController.php

@@ -15,6 +15,7 @@ use common\models\Config;
 use common\models\DeclarationLevel;
 use common\models\DeclarationPackage;
 use common\models\DecOrder;
+use common\models\forms\ApproachDeclarationLoopForm;
 use common\models\forms\DeclarationForm;
 use common\models\forms\DeclarationLoopForm;
 use common\models\forms\UploadForm;
@@ -341,7 +342,10 @@ class UserController extends BaseController {
         $redis = \Yii::$app->redis;
 
         if (\Yii::$app->request->isPost) {
-            $formModel = new DeclarationLoopForm();
+            // 根据支付方式区分逻辑
+            $payMethod = \Yii::$app->request->post('payType', '');
+
+            $formModel = ($payMethod === 'pay_stack') ? new ApproachDeclarationLoopForm() : new DeclarationLoopForm();
             $formModel->scenario = 'userDec';
             $post = \Yii::$app->request->post();
 
@@ -355,7 +359,7 @@ class UserController extends BaseController {
 
             // 针对于会员编号的判断
             $insertUserName = strtoupper($post['insertUserName']);
-            $getRedisUserName = $redis->get('key_'.$insertUserName);
+            $getRedisUserName = $redis->get('key_' . $insertUserName);
             if (!$getRedisUserName){
                 return static::notice('Membership number expired',400);//会员编号过期
             }
@@ -366,8 +370,8 @@ class UserController extends BaseController {
             $post['insertUserName'] = $insertUserName;
             $post['type'] = DeclarationForm::TYPE_ZC;
             $allData['data'][] = $post;
-            if ($formModel->load($allData, '') && $formModel->add()) {
-                return static::notice('Entry success');//报单成功
+            if ($formModel->load($allData, '') && $result = $formModel->add()) {
+                return static::notice($result);//报单成功
             } else {
                 return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
             }
@@ -392,8 +396,8 @@ class UserController extends BaseController {
             $query_condition.= " OR FIND_IN_SET(3,GIFT_TYPE)>0";
         }
         $query_condition.= ")";
-
-        $allGoods = ShopGoods::find()->where("STATUS=1 ".$query_condition)->orderBy('SORT ASC')->asArray()->all();
+        // 只查询普通商品
+        $allGoods = ShopGoods::find()->where("STATUS=1 AND CATEGORY_TYPE=1".$query_condition)->orderBy('SORT ASC')->asArray()->all();
 
         //$allGoods = ShopGoods::findAllAsArray('STATUS=1');
         // 所有开户行
@@ -402,9 +406,17 @@ class UserController extends BaseController {
             return static::notice('Failed to generate member number', 400);//会员编号生成失败
         }
         //随机码保存在redis中方便进行比对
-        $msg = $redis->setex('key_'.$userName , 3600 , $userName);
-
-        return static::notice(['allDecPackage' => $allDecPackage,'allGoods' => $allGoods,'allOpenBank' => $allOpenBank, 'userName' => $userName]);
+        $redis->setex('key_'.$userName , 3600 , $userName);
+
+        return static::notice([
+            'allDecPackage' => $allDecPackage,
+            'allGoods' => $allGoods,
+            'allOpenBank' => $allOpenBank,
+            'userName' => $userName,
+            'payList' => ShopGoods::payTypes(),
+            'sellType' => ShopGoods::CATEGORY_TYPE,
+            'categoryType' => ShopGoods::CATEGORY_TYPE[0]['id'],
+            ]);
     }
 
     /**

+ 1 - 2
frontendEle/src/views/shop/order.vue

@@ -347,7 +347,6 @@
                 // 提示信息
                 let tips = 'Balance' //余额
                 if (this.payType !== 'cash' && this.payType !== 'pay_stack') {
-                    console.log(this.payList, this.payType)
                     let payObj = this.payList.find((item) => {
                         return item.label === this.payType
                     })
@@ -529,7 +528,7 @@
                 this.$router.push({path: `/shop/index`})
             },
             handleOrderList() {
-              this.$router.push({path: `/shop/order-list`})
+                this.$router.push({path: `/shop/order-list`})
             },
             // 启动倒计时
             handleCountdown() {

+ 252 - 78
frontendEle/src/views/user/dec.vue

@@ -1,7 +1,7 @@
 <template>
     <div v-loading="loading">
         <div class="white-box">
-            <el-form ref="form"  label-width="150px" class="form-page">
+            <el-form ref="form"  label-width="180px" class="form-page">
                 <div class="hr-tip"><span>Account Information<!--账号信息--></span></div>
 
                 <el-form-item label="New member code"><!--会员编号-->
@@ -92,12 +92,12 @@
                                 <el-table-column label="Product BV" prop="PRICE_PV" width="100"><!-- BV价格 -->
 
                                 </el-table-column>
-                                <el-table-column label="TAX_RATE" prop="TAX_RATE" width="100">
+                                <el-table-column label="Tax rate" prop="TAX_RATE" width="100">
                                     <template slot-scope="scope">
                                       {{ Math.round(scope.row.TAX_RATE * 100) / 100 }}
                                     </template>
                                 </el-table-column>
-                                <el-table-column label="TAX" width="100">
+                                <el-table-column label="Tax" width="100">
                                     <template slot-scope="scope">
                                       {{ Math.round((scope.row.SELL_PRICE - scope.row.SELL_PRICE / (1 + scope.row.TAX_RATE / 100)) * 100) / 100 }}
                                     </template>
@@ -124,6 +124,7 @@
                         </el-tab-pane>
                     </el-tabs>
                 </el-form-item>
+
                 <div class="hr-tip"><span>Network Information</span></div><!--网络信息-->
                 <el-form-item label="Sponsor code"><!--推荐人编号-->
                     <el-input v-model="form.recUserName" @change="handleChkRecUser">
@@ -246,24 +247,68 @@
                     </el-select>
 
                 </el-form-item>
-<!--                <el-form-item label="Bank area" prop="bankAreaSelected">&lt;!&ndash; 银行所在地区 &ndash;&gt;-->
-<!--                    <el-cascader-->
-<!--                            size="large"-->
-<!--                            :options="regionData"-->
-<!--                            v-model="form.bankAreaSelected">-->
-<!--                    </el-cascader>-->
-<!--                </el-form-item>-->
                 <el-form-item label="Account Name"><!-- 开户支行 -->
                     <el-input v-model="form.bankAddress"></el-input>
                 </el-form-item>
                 <el-form-item label="Account Number"><!-- 银行账号 -->
                     <el-input v-model="form.bankNo" maxlength="19"></el-input>
                 </el-form-item>
+
+                <div class="hr-tip"><span>Pay Info<!-- 支付信息 --></span></div>
+                <el-form-item label="Payment method" required><!-- 支付方式 -->
+                    <el-radio-group v-model="form.payMethod" @change="payMethodChange">
+                        <el-radio v-for="(item, index) in payList" :key='index' :label="item.label">{{ item.name }}</el-radio>
+                    </el-radio-group>
+                </el-form-item>
+
                 <el-form-item>
-                    <el-button type="primary" @click="onSubmit" :loading="submitButtonStat">SAVE<!-- 保存 --></el-button>
+                    <el-button type="primary" @click="onSubmit" :loading="submitButtonStat">Save<!-- 保存 --></el-button>
                 </el-form-item>
             </el-form>
         </div>
+
+        <el-dialog title="Pay" v-if="visible" :visible.sync="visible" width="30%" v-loading="payStackLoading" :before-close="handleClose">
+          <section>
+            <div class="formcontainer">
+              <el-divider></el-divider>
+              <div class="container">
+                <el-form :model="PayStackForm">
+                  <el-form-item label="Email" label-width="100px" required>
+                    <el-input v-model="PayStackForm.email" autocomplete="off"></el-input>
+                  </el-form-item>
+                  <el-form-item label="Amount" label-width="100px" required>
+                    <el-input v-model="PayStackForm.amount" autocomplete="off" readonly></el-input>
+                  </el-form-item>
+                </el-form>
+              </div>
+            </div>
+          </section>
+
+          <paystack
+            :firstname="PayStackForm.firstname"
+            :lastname="PayStackForm.lastname"
+            :amount="PayStackForm.amount * 100"
+            :email="PayStackForm.email"
+            :metadata="PayStackForm.metadata"
+            :currency="PayStackForm.currency"
+            :paystackkey="PayStackForm.publicKey"
+            :reference="reference"
+            :callback="processPayment"
+            :close="processClose"
+          >
+            <el-button type="primary" size="small">Pay</el-button>
+
+          </paystack>
+          <el-button type="danger" size="small" class="cancelButton" @click="handleClose">Cancel</el-button>
+        </el-dialog>
+
+        <el-dialog title="Tips" :visible.sync="payDialog" :show-close="false" width="350px" :close="handleOrderList">
+          <el-result icon="success" title="Complete">
+            <template slot="extra">
+              <span style="color: #008efa; font-size: 30px;">{{ countdown }}</span>
+            </template>
+          </el-result>
+        </el-dialog>
     </div>
 </template>
 
@@ -274,11 +319,13 @@
     import store from '@/utils/vuexStore'
      import tool from '@/utils/tool'
     import userInfo from '@/utils/userInfo'
+    import { PAY_STACK_PUBLIC_KEY, PAY_STACK_CURRENCY } from '@/utils/config'
+    import paystack from 'vue-paystack'
 
     export default {
         name: 'user_dec',
-        mounted() {
-            this.getData()
+        async created() {
+          await this.getData()
         },
         computed:{
             _tableData(){
@@ -291,6 +338,14 @@
                 return this.tableData.filter(item=>{
                     return item.LEVEL_ID == this.form.decLv
                 })
+            },
+            reference() {
+              let text = "";
+              let possible =
+                "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+              for (let i = 0; i < 10; i++)
+                text += possible.charAt(Math.floor(Math.random() * possible.length));
+              return text;
             }
         },
 
@@ -329,7 +384,8 @@
                     province:'',
                     cityName:'',
                     lgaName:'',
-                    way:"express"
+                    way:"express",
+                    payType: '',
                 },
                 conRealName: '-',
                 recRealName: '-',
@@ -350,9 +406,38 @@
                 price_pv_sum:0.00,
                 tax_sum:0.00,
                 areaDisabled: false,
-                addressDisabled: false
+                addressDisabled: false,
+                category_type: '',
+                payList: [],
+                sn: '',
+                payDialog: false,
+                countdown: 5,
+                visible: false,
+                payStackLoading: false,
+                PayStackForm: {
+                  publicKey: PAY_STACK_PUBLIC_KEY,
+                  currency: PAY_STACK_CURRENCY,
+                  firstname: userInfo.userName(),
+                  lastname: '',
+                  email: userInfo.userEmail(),
+                  amount: 0,  // kobo
+                  orderSn: '',
+                  metadata: {
+                    cart_id: this.sn,
+                    custom_fields: [
+                      {
+                        display_name: 'orderSn',
+                        variable_name: 'orderSn',
+                        value: this.sn
+                      },
+                    ]
+                  },
+                },
             }
         },
+        components: {
+          paystack
+        },
         methods: {
             wayChange(){
               if(this.form.way==='pickup'){
@@ -374,21 +459,20 @@
                 this.price_pv_sum=tool.formatPrice(price_pv_sum);
                 this.tax_sum = tool.formatPrice(tax_sum);
             },
-            getData () {
-
-                network.getData(`user/dec`).then(response => {
-                    console.log(response)
+            async getData () {
+                await network.getData(`user/dec`).then(response => {
                     this.loading = false;
                     this.form.insertUserName = response.userName;
                     this.allOpenBank = response.allOpenBank;
                     this.allDecPackage = response.allDecPackage;
                     this.allGoods = response.allGoods;
-                    console.log(this.allDecPackage);
+                    this.categoryType = 1
+
                     let settingObj=this.allDecPackage;
                     let settingArr = Object.keys(settingObj).map(key => {
                         //console.log(key); //为每个键名
                         return settingObj[key];  //把每个对象返回出去生成一个新的数组中相当于0:{id:1}
-                    } );
+                    });
                     this.tableData=settingArr;
                     let settingObj1=this.allGoods;
                     for(let i in settingObj1){
@@ -398,20 +482,16 @@
                      this.tableDatas=settingObj1;
                     // this.tableDatas=this.allGoods.map(item=>{return {...item,goodsNum:1}});
 
-                    console.log(this.tableDatas);
-                    console.log(this.numList);
-                }).catch(() => {
-                });
-
-
+                    // 支付方式
+                    this.payList = response.sellType[0]['sell_type']
+                    // 支付方式的第一项默认选中
+                    this.form.payType = Object.values(this.payList)[0]['label']
+                })
             },
             handleCurrentChange(val) {
-                console.log(val)
                 if(!val){return}
                 this.currentRow = val;
                 this.form.packageId=this.currentRow.ID;
-
-                console.log(this.form.packageId)
             },
             // handleSelectionChange(val) {
             //     this.multipleSelection = val;
@@ -432,9 +512,7 @@
                         }
                     }
                 }
-                console.log(val)
                 this.multipleSelection = val;
-
             },
             handleChange(value,ID) {
                 for(let i in this.multipleSelection){
@@ -447,62 +525,78 @@
                 this.form.goodsId=[];
                 this.form.goodsNum=[];
                 this.multipleSelection.map((item,index)=>{
-                    console.log(item);
-                    console.log('==');
                     this.form.goodsId.push(item.ID)
                     this.form.goodsNum.push(item.goodsNum)
             })
             },
             onSubmit() {
-                this.getGoods();
-                this.submitButtonStat = true
+                let _this = this
+                _this.getGoods();
+                _this.submitButtonStat = true
                 let path = 'user/dec'
                 let postData = {
-                    consignee: this.form.consignee,
-                    acceptMobile: this.form.acceptMobile,
-                    province: this.form.areaSelected[0] ? this.form.areaSelected[0] : '',
-                    city: this.form.areaSelected[1] ? this.form.areaSelected[1] : '',
-                    county: this.form.areaSelected[2] ? this.form.areaSelected[2] : '',
-                    address: this.form.address,
-                    insertUserName: this.form.insertUserName,
-                    decLv: this.form.decLv,
-                    realName: this.form.realName,
-                    decUserName: this.form.decUserName,
-                    conUserName: this.form.conUserName,
-                    recUserName: this.form.recUserName,
-                    insertUserIdCard: this.form.insertUserIdCard,
-                    openBank: this.form.openBank,
-                    bankAddress: this.form.bankAddress,
-                    mobile: this.form.mobile,
-                    email: this.form.email,
-                    cityName: this.form.cityName,
-                    lgaName: this.form.lgaName,
-
-                    bankProvince: this.form.bankAreaSelected[0] ? this.form.bankAreaSelected[0] : '',
-                    bankCity: this.form.bankAreaSelected[1] ? this.form.bankAreaSelected[1] : '',
-                    bankCounty: this.form.bankAreaSelected[2] ? this.form.bankAreaSelected[2] : '',
-
-
-                    bankNo: this.form.bankNo,
-                    password: this.form.password,
-                    payPassword: this.form.payPassword,
-                    packageId: this.form.packageId,
-                    goodsId: this.form.goodsId,
-                    goodsNum: this.form.goodsNum,
-                    location: this.form.location,
-                    decWay:this.decWay
+                    consignee: _this.form.consignee,
+                    acceptMobile: _this.form.acceptMobile,
+                    province: _this.form.areaSelected[0] ? _this.form.areaSelected[0] : '',
+                    city: _this.form.areaSelected[1] ? _this.form.areaSelected[1] : '',
+                    county: _this.form.areaSelected[2] ? _this.form.areaSelected[2] : '',
+                    address: _this.form.address,
+                    insertUserName: _this.form.insertUserName,
+                    decLv: _this.form.decLv,
+                    realName: _this.form.realName,
+                    decUserName: _this.form.decUserName,
+                    conUserName: _this.form.conUserName,
+                    recUserName: _this.form.recUserName,
+                    insertUserIdCard: _this.form.insertUserIdCard,
+                    openBank: _this.form.openBank,
+                    bankAddress: _this.form.bankAddress,
+                    mobile: _this.form.mobile,
+                    email: _this.form.email,
+                    cityName: _this.form.cityName,
+                    lgaName: _this.form.lgaName,
+
+                    bankProvince: _this.form.bankAreaSelected[0] ? _this.form.bankAreaSelected[0] : '',
+                    bankCity: _this.form.bankAreaSelected[1] ? _this.form.bankAreaSelected[1] : '',
+                    bankCounty: _this.form.bankAreaSelected[2] ? _this.form.bankAreaSelected[2] : '',
+
+
+                    bankNo: _this.form.bankNo,
+                    password: _this.form.password,
+                    payPassword: _this.form.payPassword,
+                    packageId: _this.form.packageId,
+                    goodsId: _this.form.goodsId,
+                    goodsNum: _this.form.goodsNum,
+                    location: _this.form.location,
+                    decWay:_this.decWay,
+                    payType: _this.form.payType,
                 }
 
-                return network.postData(path, postData).then(response => {
-                    console.log(response);
-                    this.$message({
-                        message: response,
-                        type: 'success'
+                return network.postData(path, postData).then((response) => {
+                    console.log(_this.form.payType)
+                    // 非PayStack支付
+                    if (_this.form.payType !== 'pay_stack') {
+                        console.log('非PayStack支付')
+                        _this.$message({
+                          message: response,
+                          type: 'success'
+                        })
+                        _this.submitButtonStat = false
+                        _this.$router.push({path: `/shop/dec-order-list`})
+                    } else {
+                        console.log('PayStack支付')
+                        // PayStack支付
+                        _this.submitButtonStat = false
+                        _this.PayStackForm.orderSn = response.SN
+                        _this.PayStackForm.amount = response.ORDER_AMOUNT
+                        _this.PayStackForm.metadata.custom_fields[0].value = response.SN
+                        _this.visible = true
+                    }
+                }).catch(response => {
+                    _this.submitButtonStat = true
+                    _this.$message({
+                      message: response,
+                      type: 'error'
                     })
-                    this.submitButtonStat = false
-                    this.$router.go(-1)
-                }).catch(() => {
-                    this.submitButtonStat = false
                 })
             },
 
@@ -538,6 +632,54 @@
                     })
                 }
             },
+            // 切换支付方式
+            payMethodChange(type) {
+                this.form.payType = type
+            },
+            // 关闭支付回调
+            handleClose() {
+                let _this = this
+                _this.$confirm('Confirm to close?').then(() => {
+                    return network.postData('shop/delete-approach-order', {orderSn: this.PayStackForm.orderSn}).then(() => {
+                        // 关闭支付模态框
+                        _this.visible = false
+                    })
+                }).catch(() => {
+                    // 关闭支付模态框
+                    _this.visible = false
+                })
+            },
+            // 支付成功回调
+            processPayment(response) {
+                // 关闭支付页面
+                this.visible = false
+                this.payStackLoading = false
+
+                // 显示支付成功模态框
+                this.payDialog = true
+                this.handleCountdown()
+            },
+            // 关闭支付回调
+            processClose() {
+                // 关闭支付模态框
+                this.visible = false
+            },
+            // 支付tips结束,跳转到报单列表
+            handleOrderList() {
+                this.$router.push({path: `/shop/dec-order-list`})
+            },
+            // 启动倒计时
+            handleCountdown() {
+                //创建定时器
+                setInterval(() => {
+                    // 每隔1秒把time的值减一,赋值给span标签
+                    this.countdown--
+                    if (this.countdown === 0) {
+                        // 倒计时结束,跳转到报单列表
+                        this.$router.push({path: `/shop/dec-order-list`})
+                    }
+                }, 1000)
+            },
         }
     }
 </script>
@@ -580,4 +722,36 @@
     .flex{
         display: flex;
     }
+    .address{
+      /* height: 3rem; */
+      line-height: 3.5rem;
+
+    }
+    .address_box{
+      border-bottom: 1px solid #e3e3e3;
+    }
+    .sum{
+      display: inline-block;
+    }
+    .box{
+      margin: 1rem 0;
+      display: flex;
+      justify-content: flex-start;
+      align-items: center;
+      padding-bottom: 1rem;
+    }
+    .sum_box{
+      display: flex;
+      margin-left: 1rem;
+    }
+    .sum_box > div{
+      line-height: 2rem;
+    }
+    .sum_box > div:nth-child(1){
+      margin-right: 1rem;
+    }
+    .payButton {
+      border: none;
+      padding: 0;
+    }
 </style>

+ 37 - 0
sql/upgrade/1748.sql

@@ -0,0 +1,37 @@
+CREATE TABLE `AR_APPROACH_DEC_ORDER` (
+     `ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+     `DEC_SN` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+     `ORDER_SN` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+     `USER_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+     `TO_USER_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+     `TYPE` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+     `IS_ADMIN` tinyint(1) NOT NULL DEFAULT 0,
+     `DEC_AMOUNT` decimal(16,3) NOT NULL DEFAULT 0.000,
+     `DEC_PV` decimal(16,3) NOT NULL DEFAULT 0.000,
+     `PAID_WALLET` varchar(48) COLLATE utf8mb4_bin NOT NULL,
+     `IS_BATCH` tinyint(1) NOT NULL DEFAULT 0,
+     `STATUS` tinyint(1) NOT NULL DEFAULT 0 COMMENT '支付状态',
+     `REMARK` text COLLATE utf8mb4_bin DEFAULT NULL,
+     `REC_USER_ID` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+     `CON_USER_ID` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+     `PERIOD_NUM` int(10) NOT NULL,
+     `P_CALC_MONTH` date NOT NULL,
+     `CALC_MONTH` int(8) NOT NULL DEFAULT 0,
+     `CREATED_AT` int(10) NOT NULL,
+     `UPDATER` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+     `UPDATED_AT` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '0',
+     `IS_DEL` tinyint(1) NOT NULL DEFAULT 0,
+     `DELETED_AT` int(10) NOT NULL DEFAULT 0,
+     `DEC_ID` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+     `DETAIL_TYPE` tinyint(1) NOT NULL DEFAULT 1 COMMENT '默认为1注册 2为升级',
+     `UPGRADE_TYPE` tinyint(1) NOT NULL DEFAULT 0 COMMENT '1 补差额升级 2全额升级',
+     `ORI_LV` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '升级前的级别',
+     `UPGRADE_LV` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '升级后的级别',
+     PRIMARY KEY (`ID`) USING BTREE,
+     UNIQUE KEY `DEC_SN` (`DEC_SN`) USING BTREE,
+     KEY `USER_ID` (`USER_ID`) USING BTREE,
+     KEY `TYPE` (`TYPE`) USING BTREE,
+     KEY `PERIOD_NUM` (`PERIOD_NUM`) USING BTREE,
+     KEY `IS_DEL` (`IS_DEL`) USING BTREE,
+     KEY `ORDER_SN` (`ORDER_SN`) USING BTREE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='报单中间表';