Explorar o código

会员升级单增加PayStack支付方式

kevin_zhangl %!s(int64=3) %!d(string=hai) anos
pai
achega
0eae20cfa8

+ 2 - 3
common/libs/export/BaseExport.php

@@ -799,9 +799,8 @@ ORDER;
             $pdf->AddPage();
             // 设置字体
             $pdf->SetFont('stsongstdlight', '', 10, '', true);
-            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
-            $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
-            $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
+//            $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+//            $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
             $pdf->writeHTML($context);
             $pdf->Output($realFile, 'F');
 

+ 4 - 0
common/models/ApproachDecOrder.php

@@ -30,6 +30,10 @@ use Yii;
  * @property string $UPDATED_AT 更新时间
  * @property int $IS_DEL 是否删除
  * @property int $DELETED_AT 删除时间
+ * @property int $DETAIL_TYPE 类型
+ * @property int $UPGRADE_TYPE 升级类型
+ * @property string $ORI_LV 升级前级别
+ * @property string $UPGRADE_LV 升级后级别
  */
 class ApproachDecOrder extends \common\components\ActiveRecord
 {

+ 432 - 0
common/models/forms/ApproachDeclarationUpgradeForm.php

@@ -0,0 +1,432 @@
+<?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\Info;
+use common\models\ApproachDecOrder;
+use common\models\ApproachOrder;
+use common\models\ApproachOrderGoods;
+use common\models\Config;
+use common\models\DeclarationLevel;
+use common\models\DeclarationPackage;
+use common\models\DecLevelLog;
+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\Region;
+use common\models\ShopGoods;
+use common\models\User;
+use common\models\UserInfo;
+use common\models\UserNetwork;
+use yii\base\Exception;
+
+/**
+ * 升级管理,进行升级
+ */
+class ApproachDeclarationUpgradeForm extends Model
+{
+    public $type;
+    public $decLv;
+    public $decWay;
+    public $packageId;
+    public $goodsId;
+    public $goodsNum;
+    public $insertUserName;
+    public $consignee;
+    public $acceptMobile;
+    public $province;
+    public $city;
+    public $county;
+    public $lgaName;
+    public $cityName;
+    public $address;
+    public $nowPerf;
+    public $nextPerf;
+    public $decUserName;
+    public $remark;
+    public $payType;
+    // 传过来的全部数据
+    public $allData;
+    private $_decId;
+    public $_insertUserId;
+    private $_decAmount;
+    private $_decPv;
+    private $_orderGoods;
+    
+    const TYPE_ZC = 'ZC';
+    private $_userForm = null;
+    // 全部的安置网上级
+    private $_tempNetworkParentUser = [];
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['remark','type','decLv','decWay','packageId','goodsId', 'goodsNum', 'insertUserName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','address','nowPerf','nextPerf'], 'trim'],
+            [['type','decLv','decWay','insertUserName','nowPerf','province',/*'city','county',*/'address','acceptMobile'], 'required'],
+            [['decUserName'], 'issetDec'], // 必须是报单中心
+            [['decWay'], 'hasProduct'],// 必须选择商品
+            [['decLv'], 'alreadyMaxDec'], //判断要升级用户是否已经是最高级
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'type' => 'Upgrade type',//升级类型
+            'decLv' => 'Upgrade level',//升级级别
+            'decWay' => 'Declaration method',//报单方式
+            'packageId' => 'Upgrade package',//升级套餐
+            'goodsId' => 'Product ID',//商品ID
+            'goodsNum' => 'Product quantity',//商品数量
+            'insertUserName' => 'Member number to be upgraded',//要升级的会员编号
+            'consignee' => 'consignee',//收货人
+            'acceptMobile' => 'The phone number of Consignee',//收货人手机
+            'province' => 'Receiving Province',//收货省
+            'city' => 'Receiving City',//收货市
+            'county' => 'Receiving area / county',//收货区县
+            'lgaName' => 'Local Government Area',
+            'cityName' => 'City',
+            'address' => 'Receiving detailed address',//收货详细地址
+        ];
+    }
+
+    /**
+     * 添加报单
+     * @param $allData
+     * @throws Exception
+     * @throws \yii\db\Exception
+     */
+    public function add($allData){
+        if(!$this->validate()){
+            return null;
+        }
+        // 首购单
+        if($this->type == self::TYPE_ZC){
+            //报单商品及PV判断
+            $decLevelConfig = Cache::getDecLevelConfig();
+            $decLevel = $decLevelConfig[$this->decLv];
+            $toDecLevel = $this->decLv;
+            if(!$this->decLv){
+                throw new Exception('Please select upgrade level');//请选择升级级别
+            }
+            $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
+            $userId = $baseInfo['ID'];
+            $userDecPvSum = User::sumDevPvByUserId($userId); // 用户所有报单PV总和
+            if ($userDecPvSum != $this->nowPerf) {
+                throw new Exception('Please contact the customer service personnel to check the performance of upgraded members');//请联系客服人员核对升级会员业绩
+            }
+            // 获取用户是否是观察期
+            $observe = Config::getConfigByType('observe'); // 获取观察期配置信息
+            $observeLimit = $observe['observePeriodLimit']['value']; // 月份限制
+            $isObserve = User::checkIsObserve($baseInfo['CREATED_AT'], $observeLimit); // 判断用户是否再观察期中
+            $diffPerf = $isObserve ? $this->nowPerf : 0; // 观察期内升级要加上用户累计的PV,全额则基础PV为0,全额购买
+            if ($this->decWay != 2) {
+                throw new Exception('The upgrade method is incorrect. Please contact the customer service personnel');//升级方式不正确,请联系客服人员
+            }
+            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']
+                // ];
+            } 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' => Info::getUserEmailByUserId(\Yii::$app->user->id) ?? '',
+                                'TAX_RATE' => $goods['TAX_RATE'],
+                            ];
+                        }
+                    }
+                }
+                // 这里特殊是用户原报单PV之和+用户购买的商品总PV
+                $checkPv = $totalPv + $diffPerf;
+                if($checkPv < $decLevel['PERF']) {
+                    throw new Exception('Total PV cannot be less than the selected level PV');//总PV不能小于所选级别PV
+                }
+                foreach ($decLevelConfig as $key=>$val){
+                    if($checkPv>=$val['PERF']){
+                        $toDecLevel = $key;
+                    }
+                }
+                if($this->decLv!=$toDecLevel){
+                    throw new Exception('The total PV cannot exceed the PV value of the next level under the selected level');//总PV不能超过已选级别下一个级别的PV值
+                }
+                $this->_decAmount = $totalAmount;
+                $this->_decPv = $totalPv;
+            }
+
+            $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
+            $this->_insertUserId = $baseInfo['ID']; // 被报单人,通过insername 查找用户id
+            $insertConId = $baseInfo['CON_UID'];
+            $insertRecId = $baseInfo['REC_UID'];
+            $decResult = $this->addDecOrder($insertConId, $insertRecId, $baseInfo['DEC_LV'], $isObserve, $this->remark);
+            if (!$decResult) {
+                throw new Exception("operation failed");//操作失败
+            }
+            return $decResult;
+        }
+        return true;
+    }
+
+    /**
+     * 添加报单订单
+     * @throws Exception|\Throwable
+     */
+    public function addDecOrder($insertConId, $insertRecId, $oriDecLv, $isObserve, $remark = ''): ApproachOrder
+    {
+        $warehouse = Region::getWarehouseByCode($this->province);//仓库
+        if(!$warehouse){
+            throw new Exception('Delivery is temporarily not supported in the region. Contact customer service for details');//地区暂时不支持配送,具体联系客服
+        }
+
+        $upgradeType = $isObserve ? 1 : 2; // 1补差  2全额
+        $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);
+
+        // 加入报单信息
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            $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 = 'cash';
+            $decOrderModel->CON_USER_ID = $insertConId;
+            $decOrderModel->REC_USER_ID = $insertRecId;
+            $decOrderModel->DEC_ID = $this->_decId;
+            $decOrderModel->IS_DEL = 0;
+            $decOrderModel->DETAIL_TYPE = 2;
+            $decOrderModel->CREATED_AT = Date::nowTime();
+            $decOrderModel->UPGRADE_TYPE = $upgradeType;
+            $decOrderModel->REMARK = $remark;
+            $decOrderModel->ORI_LV = $oriDecLv; // 变更前的级别
+            $decOrderModel->UPGRADE_LV = $this->decLv; // 变更后的级别
+            if (!$decOrderModel->save()) {
+                $transaction->rollBack();
+                throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
+            }
+
+            $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 = 'pay_stack';
+            $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->LGA_NAME = $this->lgaName;
+            $orderModel->CITY_NAME = $this->cityName;
+            $orderModel->ADDRESS = $this->address;
+            $orderModel->WAREHOUSE = $warehouse;
+            $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
+            $orderModel->CREATED_AT = Date::nowTime();
+            $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
+            $orderModel->EMAIL = Info::getUserEmailByUserId(\Yii::$app->user->id) ?? '';
+            if(!$orderModel->save()){
+                $transaction->rollBack();
+                throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
+            }
+
+            foreach ($this->goodsNum as $k => $v) {
+                if ($v) {
+                    $goods = ShopGoods::findOneAsArray('ID=:ID',[':ID'=> $this->goodsId[$k]]);
+                    $storenums = $goods['STORE_NUMS'] - $this->goodsNum[$k];
+                    if($goods['STATUS']==1){
+                        if($goods['STORE_NUMS'] >=$this->goodsNum[$k]) {
+                            $data = ShopGoods::find()->where(['ID' => $this->goodsId[$k]])->one();
+                            $data->STORE_NUMS = $storenums;
+                            $data->update();
+
+                            if ($storenums==0) {
+                                $data->STATUS = 0;
+                                $data->UPDATED_AT = Date::nowTime();
+                                $data->update();
+                            }
+                        } else {
+                            throw new Exception("product".$goods['GOODS_NAME']."Insufficient inventory");//"商品".$goods['GOODS_NAME']."库存不足"
+                        }
+                    } else {
+                        throw new Exception("product".$goods['GOODS_NAME']."Removed from the shelf");// "商品".$goods['GOODS_NAME']."已下架"
+                    }
+                }
+            }
+
+            // 加入商品到订单商品表
+            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);
+
+            //写入收货地址信息
+            $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->LGA_NAME = $this->lgaName;
+            $addressModel->CITY_NAME = $this->cityName;
+            $addressModel->ADDRESS = $this->address;
+            $addressModel->IS_DEFAULT = 0;
+            if (!$addressModel->save()) {
+                $transaction->rollBack();
+                throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
+            }
+
+            $transaction->commit();
+
+            return $orderModel;
+        } catch(Exception $e) {
+            $transaction->rollBack();
+            throw new Exception($e->getMessage());
+        }
+    }
+
+    /**
+     * 判断报单中心是否存在
+     * @param $attribute
+     * @return false|void
+     */
+    public function issetDec($attribute){
+        $decUser = User::find()
+        ->select('ID')
+        ->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])
+        ->asArray()
+        ->one();
+        if (!$decUser) {
+            $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]));
+//            if (!isset($flipParent[$this->decUserName])) {
+////                $this->addError($attribute, '为' . $this->insertUserName . '升级报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
+//                $this->addError($attribute, 'by' . $this->insertUserName . 'Upgrade declaration, declaration Center' . $this->decUserName . 'be not in' . $this->insertUserName . 'Online level of resettlement');
+//                return ;
+//            }
+            $this->_decId = $decUser['ID'];
+        }
+    }
+
+
+    // 判断是否已选择商品或套餐
+    public function hasProduct($attribute) {
+        if ($this->decWay==1 && empty($this->packageId)) {
+            $this->addError($attribute, 'Purchase package upgrade, please select package');//购买套餐升级,请选择套餐
+            return false;
+        }
+        if ($this->decWay!=1 && empty($this->goodsId)) {
+            $this->addError($attribute, 'Purchase product upgrade, please select product');//购买商品升级,请选择商品'
+            return false;
+        }
+
+        return true;
+    }
+
+    // 判断要升级的会员,是否已是最高级别
+    public function alreadyMaxDec($attribute) {
+        $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
+        $userDecId = $baseInfo['DEC_LV'];// 用户当前的级别
+        $maxPerfInfo = DeclarationLevel::getMaxDecPref(); 
+        $maxDecId = $maxPerfInfo['ID']; // 级别配置中最高级别ID
+        if ($maxDecId == $userDecId) {
+            $this->addError($attribute, 'It is already the highest level and no upgrade is required');//已是最高级别,无需升级
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * 寻找被升级人的上级
+     * @param null $conUserName
+     * @return bool
+     */
+    private function loopFindParentToNetwork($conUserName = null) {
+        if($conUserName == null ){
+            $conUserName = $this->insertUserName;
+        }
+        $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);
+                if (is_null($parentBaseUser)) {
+                    continue;
+                }
+                $this->_tempNetworkParentUser[$this->insertUserName][] = $parentBaseUser['USER_NAME'] ;
+
+                unset($parentUserId, $parentBaseUser);
+            }
+        }
+        unset($allParentUserIds);
+        
+        return true;
+    }
+}

+ 23 - 4
common/models/forms/ApproachOrderForm.php

@@ -15,6 +15,7 @@ use common\models\ApproachDecOrder;
 use common\models\ApproachOrder;
 use common\models\ApproachOrderGoods;
 use common\models\DealType;
+use common\models\DecLevelLog;
 use common\models\DecOrder;
 use common\models\Order;
 use common\models\OrderGoods;
@@ -319,12 +320,30 @@ class ApproachOrderForm extends Model
             }
             OrderGoods::batchInsert($approachOrderGoods);
             // 同步报单
-            $approachDecOrder = ApproachDecOrder::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+            $approachDecOrder = ApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
             if ($approachDecOrder) {
-                foreach ($approachDecOrder as &$decOrder) {
-                    unset($decOrder['STATUS']);
+                unset($approachDecOrder['STATUS']);
+                // 同步报单
+                DecOrder::insertOne($approachDecOrder);
+
+                // 会员升级 报单类型:2会员升级单
+                if ($approachDecOrder['DETAIL_TYPE'] == 2) {
+                    // 为被升级人进行升级操作
+                    $decLevelLog = new DecLevelLog();
+                    $decLog = [
+                        'userId' => $approachDecOrder['TO_USER_ID'],//会员ID
+                        'fromId' => $approachDecOrder['ORI_LV'], // 变动前的级别
+                        'levelId' => $approachDecOrder['UPGRADE_LV'],// 变动后的级别
+                        'actionId' => $approachDecOrder['USER_ID'],
+                        'remark' => $approachDecOrder['REMARK'],
+                        'lvPv' => $this->_model->PV,
+                    ];
+                    $modifyDecLv = $decLevelLog->frontendChange($decLog);
+                    if (empty($modifyDecLv)) {
+                        $transaction->rollBack();
+                        throw new Exception("Failed to upgrade for member");//为会员升级失败
+                    }
                 }
-                DecOrder::batchInsert($approachDecOrder);
             }
 
             // 删除中间表

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

@@ -165,7 +165,9 @@ class DeclarationUpgradeForm extends Model
                                 'POINT' => $goods['POINT'],
                                 'BUY_NUMS' => intval($v),
                                 'SKU_CODE' => $goods['GOODS_NO'],
-                                'GOODS_TITLE' => $goods['GOODS_NAME']
+                                'GOODS_TITLE' => $goods['GOODS_NAME'],
+                                'EMAIL' => Info::getUserEmailByUserId(\Yii::$app->user->id) ?? '',
+                                'TAX_RATE' => $goods['TAX_RATE'],
                             ];
                         }
                     }
@@ -443,6 +445,7 @@ class DeclarationUpgradeForm extends Model
         if($allParentUserIds){
             foreach($allParentUserIds as $parentUserId) {
                 $parentBaseUser = Info::getBaseUserById($parentUserId);
+                if (is_null($parentBaseUser)) continue;
                 $this->_tempNetworkParentUser[$this->insertUserName][] = $parentBaseUser['USER_NAME'] ;
 
                 unset($parentUserId, $parentBaseUser);

+ 4 - 6
frontendApi/modules/v1/controllers/ShopController.php

@@ -707,9 +707,8 @@ ORDER;
         $pdf->AddPage();
         // 设置字体
         $pdf->SetFont('stsongstdlight', '', 10, '', true);
-        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
-        $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
-        $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
+//        $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+//        $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
         $pdf->writeHTML($context);
 
         ob_clean();
@@ -954,9 +953,8 @@ ORDER;
         $pdf->AddPage();
         // 设置字体
         $pdf->SetFont('stsongstdlight', '', 10, '', true);
-        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
-        $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
-        $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
+//        $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+//        $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
         $pdf->writeHTML($context);
 
         ob_clean();

+ 25 - 6
frontendApi/modules/v1/controllers/UserController.php

@@ -10,12 +10,14 @@ namespace frontendApi\modules\v1\controllers;
 
 use common\helpers\Cache;
 use common\helpers\Form;
+use common\helpers\Tool;
 use common\helpers\user\Info;
 use common\models\Config;
 use common\models\DeclarationLevel;
 use common\models\DeclarationPackage;
 use common\models\DecOrder;
 use common\models\forms\ApproachDeclarationLoopForm;
+use common\models\forms\ApproachDeclarationUpgradeForm;
 use common\models\forms\DeclarationForm;
 use common\models\forms\DeclarationLoopForm;
 use common\models\forms\UploadForm;
@@ -296,12 +298,19 @@ class UserController extends BaseController {
         }
         // 开始升级
         if (\Yii::$app->request->isPost) {
-            $formModel = new DeclarationUpgradeForm();
             $post = \Yii::$app->request->post();
+            // 根据支付方式区分逻辑
+            $payMethod = \Yii::$app->request->post('payType', '');
+            if ($payMethod === 'pay_stack') {
+                $formModel = new ApproachDeclarationUpgradeForm();
+            } else {
+                unset($post['payType']);
+                $formModel = new DeclarationUpgradeForm();
+            }
+
             $post['type'] = DeclarationForm::TYPE_ZC;
-            $allData['data'][] = $post;
-            if ($formModel->load($post, '') && $formModel->add($post)) {
-                return static::notice('Upgrade declaration succeeded');//升级报单成功
+            if ($formModel->load($post, '') && $result = $formModel->add($post)) {
+                return static::notice($result);// Upgrade declaration succeeded升级报单成功
             } else {
                 return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
             }
@@ -328,9 +337,19 @@ class UserController extends BaseController {
         }
         $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();
+        foreach ($allGoods as &$goods) {
+            $goods['TAX'] = Tool::calculateTax($goods['SELL_PRICE'], $goods['TAX_RATE']);
+        }
 
-        return static::notice(['allDecPackage' => $allDecPackage,'allGoods' => $allGoods,'decUserName'=>$decUserName]);
+        return static::notice([
+            'allDecPackage' => $allDecPackage,
+            'allGoods' => $allGoods,
+            'decUserName'=>$decUserName,
+            'payList' => ShopGoods::payTypes(),
+            'sellType' => ShopGoods::CATEGORY_TYPE,
+            'categoryType' => ShopGoods::CATEGORY_TYPE[0]['id'],
+        ]);
     }
 
     /**

+ 5 - 0
frontendEle/src/utils/tool.js

@@ -210,6 +210,11 @@ let tool = {
         if (hasStatusBar) return window.innerHeight - 320
         return window.innerHeight - 260
     },
+  // 计算商品税额
+  calculateTax(amount, taxRate, count = 1) {
+      let taxAmount = (amount - amount / (1 + taxRate / 100)) * count
+      return Math.round(taxAmount * 100) / 100
+  },
 }
 
 export default tool

+ 3 - 0
frontendEle/src/views/shop/order.vue

@@ -172,6 +172,7 @@
           :reference="reference"
           :callback="processPayment"
           :close="processClose"
+          :channels="channels"
       >
         <el-button type="primary" size="small">Pay</el-button>
       </paystack>
@@ -224,6 +225,8 @@ export default{
       countdown: 5,
       visible: false,
       payStackLoading: false,
+      // channels: ['card', 'bank', 'USSD', 'QR'],
+      channels: ['card', 'bank'],
       form: {
         publicKey: PAY_STACK_PUBLIC_KEY,
         currency: PAY_STACK_CURRENCY,

+ 181 - 17
frontendEle/src/views/user/upgrade.vue

@@ -55,7 +55,7 @@
                     <template slot="label">
                         Upgrade purchase product<!-- 升级购买商品 -->
                     </template>
-                    <el-tabs type="border-card" v-model="decWay" style="position: relative;width: 600px;">
+                    <el-tabs type="border-card" v-model="decWay" style="position: relative;width: 100%;">
                         <!--<el-tab-pane name="1">
                             <span slot="label">套餐</span>
                             <el-table class="table-box" :data="_tableData" stripe style="width: 100%;" highlight-current-row @current-change="handleCurrentChange">
@@ -97,19 +97,29 @@
                                         width="55">
                                 </el-table-column>
 
-                                <el-table-column label="product name" prop="GOODS_NAME"><!-- 商品名称 -->
+                                <el-table-column label="product Name" prop="GOODS_NAME"><!-- 商品名称 -->
 
                                 </el-table-column>
-                                <el-table-column label="product code" prop="GOODS_NO"><!-- 商品编号 -->
+                                <el-table-column label="product Code" prop="GOODS_NO"><!-- 商品编号 -->
 
                                 </el-table-column>
-                                <el-table-column label="product price" prop="SELL_PRICE"><!-- 产品价格 -->
+                                <el-table-column label="product Price" prop="SELL_PRICE"><!-- 产品价格 -->
 
                                 </el-table-column>
                                 <el-table-column label="product BV" prop="PRICE_PV"><!-- BV价格 -->
 
                                 </el-table-column>
-                                <el-table-column label="quantity" width="150"><!-- 数量 -->
+                                <el-table-column label="Tax Rate"><!--税率-->
+                                    <template slot-scope="scope">
+                                        <span>{{ Math.round(scope.row.TAX_RATE * 100) / 100 }}</span>
+                                    </template>
+                                </el-table-column>
+                                <el-table-column label="Tax"><!--税额-->
+                                    <template slot-scope="scope">
+                                        <span>{{ Math.round(scope.row.TAX * 100) / 100 }}</span>
+                                    </template>
+                                </el-table-column>
+                                <el-table-column label="Qty" width="150"><!-- 数量 -->
                                     <template slot-scope="scope">
                                         <el-input-number size="mini" v-model="numList[scope.$index]"  :min="0" :max="Number(scope.row.STORE_NUMS)" @change="value=>{handleChange(value,scope.row.ID)}"></el-input-number>
                                     </template>
@@ -168,11 +178,60 @@
                 <el-form-item v-if="!isMax" label="note"><!-- 备注 -->
                     <el-input type="textarea" v-model="form.remark"></el-input>
                 </el-form-item>
+
+                <el-form-item v-if="!isMax" label="Payment method" required><!-- 支付方式 -->
+                  <el-radio-group v-model="form.payType" @change="payMethodChange">
+                    <el-radio v-for="(item, index) in payList" :key='index' :label="item.label">{{ item.name }}</el-radio>
+                  </el-radio-group>
+                </el-form-item>
+
                 <el-form-item v-if="!isMax">
                     <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="the order is successful">
+            <template slot="extra">
+              <span style="color: #008efa; font-size: 30px;">{{ countdown }}</span>
+            </template>
+          </el-result>
+        </el-dialog>
     </div>
 </template>
 
@@ -181,7 +240,10 @@
     import network from '@/utils/network'
     import baseInfo from '@/utils/baseInfo'
     import store from '@/utils/vuexStore'
-     import tool from '@/utils/tool'
+    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_upgrade',
@@ -199,6 +261,13 @@
                 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;
             }
         },
 
@@ -240,7 +309,7 @@
                     lgaName:'',
                     cityName:'',
                     acceptMobile:'',
-
+                    payType: '',
                 },
                 num: 1,
                 tableData:null,
@@ -254,9 +323,37 @@
                 goodsNums:[],
                 numList: [],
                 sell_price_sum:0.00,
-                price_pv_sum:0.00
+                price_pv_sum:0.00,
+                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: {
             // 获取要升级的会员信息
             upgradeInfo() {
@@ -306,6 +403,10 @@
                     }
                     this.tableDatas=settingObj1;
 
+                  // 支付方式
+                  this.payList = response.sellType[0]['sell_type']
+                  // 支付方式的第一项默认选中
+                  this.form.payType = Object.values(this.payList)[0]['label']
                 }).catch(() => {
                 });
             },
@@ -388,17 +489,27 @@
                     lgaName: this.form.lgaName,
                     cityName: this.form.cityName,
                     nowPerf:this.nowPerf,
-                    nextPerf:this.nextPerf
+                    nextPerf:this.nextPerf,
+                    payType: this.form.payType,
                 }
 
                 return network.postData(path, postData).then(response => {
-                    console.log(response);
-                    this.$message({
-                        message: response,
-                        type: 'success'
-                    })
-                    this.submitButtonStat = false
-                    this.$router.go(-1)
+                    // 非PayStack支付
+                    if (this.form.payType !== 'pay_stack') {
+                        this.$message({
+                          message: response,
+                          type: 'success'
+                        })
+                        this.submitButtonStat = false
+                        this.$router.push({path: `/shop/order-list`})
+                    } else {
+                        // PayStack支付
+                        this.submitButtonStat = false
+                        this.PayStackForm.orderSn = response.SN
+                        this.PayStackForm.amount = response.ORDER_AMOUNT
+                        this.PayStackForm.metadata.custom_fields[0].value = response.SN
+                        this.visible = true
+                    }
                 }).catch(() => {
                     this.submitButtonStat = false
                 })
@@ -436,6 +547,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>
@@ -473,7 +632,8 @@
         padding-right: 30px;}
     .el-tabs--border-card{
         position: relative;
-    width: 600px;
+      width: 100%;
+    /*width: 600px;*/
     }
     .flex{
         display: flex;
@@ -481,4 +641,8 @@
     .form-page{
         width:100% !important;
     }
+    .payButton {
+      border: none;
+      padding: 0;
+    }
 </style>