Browse Source

Merge branch 'feature/EK-5822' of guanli/ngds into master

ryan001 38 minutes ago
parent
commit
eadedf45fb

+ 2 - 0
.gitignore

@@ -119,3 +119,5 @@ vendor/yiisoft/yii2/di/Instance.php
 vendor/yiisoft/yii2/di/NotInstantiableException.php
 vendor/yiisoft/yii2/di/ServiceLocator.php
 frontendApi/runtime/logs/
+
+docs

+ 1 - 1
common/config/main.php

@@ -63,7 +63,7 @@ return [
                 'port' => 325,
                 'username' => 'ac71555',
                 'password' => 'I1j-MKi-fJ8-nHb',
-                'encryption' => 'TLS',
+//                'encryption' => 'TLS',
             ],
         ],
         'swooleAsyncTimer' => [

+ 1 - 0
common/helpers/Email.php

@@ -31,5 +31,6 @@ class Email
             ->send();
 
         LoggerTool::debug('sendRegistrationEmail' . sprintf('sendRegistrationEmail: %s', json_encode([$email, $userName, $password, $response])));
+        return $response;
     }
 }

+ 41 - 0
common/helpers/GuestDeclarationDraftStatus.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace common\helpers;
+
+final class GuestDeclarationDraftStatus
+{
+    const DRAFT = 'draft';
+    const PENDING_PAYMENT = 'pending_payment';
+    const PROCESSING = 'processing';
+    const COMPLETED = 'completed';
+    const PAYMENT_FAILED = 'payment_failed';
+    const PAYMENT_INITIALIZING = 'payment_initializing';
+    const EXPIRED = 'expired';
+    const MANUAL_REVIEW = 'manual_review';
+
+    private const TRANSITIONS = [
+        self::DRAFT => [self::PAYMENT_INITIALIZING, self::EXPIRED],
+        self::PENDING_PAYMENT => [self::PROCESSING, self::PAYMENT_FAILED, self::PAYMENT_INITIALIZING, self::EXPIRED, self::MANUAL_REVIEW],
+        self::PAYMENT_INITIALIZING => [self::DRAFT, self::PENDING_PAYMENT, self::MANUAL_REVIEW],
+        self::PROCESSING => [self::COMPLETED, self::MANUAL_REVIEW],
+        self::PAYMENT_FAILED => [self::PAYMENT_INITIALIZING, self::EXPIRED],
+        self::COMPLETED => [],
+        self::EXPIRED => [],
+        self::MANUAL_REVIEW => [],
+    ];
+
+    public static function all(): array
+    {
+        return array_keys(self::TRANSITIONS);
+    }
+
+    public static function canTransition(string $from, string $to): bool
+    {
+        return in_array($to, self::TRANSITIONS[$from] ?? [], true);
+    }
+
+    public static function isExpired(?int $expiresAt, ?int $now = null): bool
+    {
+        return $expiresAt !== null && $expiresAt <= ($now ?? time());
+    }
+}

+ 25 - 4
common/helpers/PayStack.php

@@ -4,6 +4,11 @@ namespace common\helpers;
 
 class PayStack
 {
+    public static function verifyWebhookSignature(string $rawBody, string $signature, string $secretKey): bool
+    {
+        return $signature !== '' && hash_equals(hash_hmac('sha512', $rawBody, $secretKey), $signature);
+    }
+
     /**
      * 根据运行环境加载secretKey
      */
@@ -16,17 +21,24 @@ class PayStack
     /**
      * 支付.
      */
-    public static function transactionInit($currency, $amount, $email)
+    public static function transactionInit($currency, $amount, $email, array $metadata = [], string $reference = '')
     {
         $secretKey = self::getSecretKey();
 
         LoggerTool::info('env: ' . YII_ENV);
 
         if (YII_ENV != YII_ENV_PROD) {
+            if ($reference === '') {
+                $reference = bin2hex(random_bytes(16));
+            }
             return [
                 'status' => true,
                 'data' => [
-                    'amount' => $amount
+                    'amount' => (int) round($amount * 100),
+                    'currency' => strtoupper((string) $currency),
+                    'reference' => $reference,
+                    'authorization_url' => 'https://checkout.paystack.com/' . $reference,
+                    'access_code' => $reference,
                 ]
             ];
         }
@@ -35,8 +47,15 @@ class PayStack
             $url = "https://api.paystack.co/transaction/initialize";
             $fields = [
                 'email' => $email,
-                'amount' => $amount * 100
+                'amount' => (int) round($amount * 100),
+                'currency' => strtoupper((string) $currency),
             ];
+            if ($reference !== '') {
+                $fields['reference'] = $reference;
+            }
+            if ($metadata) {
+                $fields['metadata'] = json_encode($metadata, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+            }
             $fields_string = http_build_query($fields);
             //open connection
             $curl = curl_init();
@@ -51,6 +70,8 @@ class PayStack
             ));
             //So that curl_exec returns the contents of the cURL; rather than echoing it
             curl_setopt($curl,CURLOPT_RETURNTRANSFER, true);
+            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
+            curl_setopt($curl, CURLOPT_TIMEOUT, 30);
             //execute post
             $result = curl_exec($curl);
             $err = curl_error($curl);
@@ -167,4 +188,4 @@ class PayStack
             ];
         }
     }
-}
+}

+ 19 - 6
common/helpers/Tool.php

@@ -582,14 +582,27 @@ class Tool {
     public static function approachOrderCall($call)
     {
         try {
+            $data = $call['data'] ?? [];
+            $customFields = $data['metadata']['custom_fields'] ?? [];
+            $safeData = [
+                'id' => $data['id'] ?? null,
+                'status' => $data['status'] ?? null,
+                'reference' => $data['reference'] ?? '',
+                'amount' => $data['amount'] ?? null,
+                'currency' => $data['currency'] ?? null,
+                'paid_at' => $data['paid_at'] ?? null,
+                'metadata' => ['custom_fields' => [
+                    ['value' => $customFields[0]['value'] ?? ''],
+                    ['value' => $customFields[1]['value'] ?? ''],
+                ]],
+            ];
             $model = new ApproachOrderCall();
-            $model->sn = $call['data']['metadata']['custom_fields'][0]['value'] ?? '';
-            $model->reference = $call['data']['reference'] ?? '';
-            $model->event = $call['event'];
-            $model->data = $call['data'];
+            $model->sn = $safeData['metadata']['custom_fields'][0]['value'];
+            $model->reference = $safeData['reference'];
+            $model->event = $call['event'] ?? '';
+            $model->data = $safeData;
             $model->insert();
         } catch (Exception $e) {
-            LoggerTool::info($call);
             LoggerTool::error(sprintf('[%s] [%s] [%s]', $e->getFile(), $e->getLine(), $e->getMessage()));
         }
     }
@@ -658,4 +671,4 @@ class Tool {
 
         return $prefix . $currentDate . $no;
     }
-}
+}

+ 2 - 1
common/models/ApproachDecOrder.php

@@ -52,7 +52,8 @@ class ApproachDecOrder extends \common\components\ActiveRecord
     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'],
+            [['TO_USER_ID','REC_USER_ID',/*'CON_USER_ID','DEC_ID', */'TYPE', 'PAID_WALLET', 'PERIOD_NUM', 'P_CALC_MONTH', 'CREATED_AT'], 'required'],
+            [['USER_ID'], '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],

+ 83 - 0
common/models/GuestDeclarationDraft.php

@@ -0,0 +1,83 @@
+<?php
+
+namespace common\models;
+
+use common\components\ActiveRecord;
+use common\helpers\GuestDeclarationDraftStatus;
+use Yii;
+
+/**
+ * Durable state for an unauthenticated registration order awaiting payment.
+ */
+class GuestDeclarationDraft extends ActiveRecord
+{
+    public static function tableName()
+    {
+        return '{{%GUEST_DECLARATION_DRAFT}}';
+    }
+
+    public function rules()
+    {
+        return [
+            [['ORDER_SN', 'ACCESS_TOKEN_HASH', 'PAYLOAD', 'ORDER_SNAPSHOT', 'STATUS', 'PAY_AMOUNT', 'CURRENCY', 'CREATED_AT', 'EXPIRES_AT'], 'required'],
+            [['PAYLOAD', 'ORDER_SNAPSHOT', 'PAYMENT_NOTE'], 'string'],
+            [['PAY_AMOUNT'], 'number'],
+            [['CREATED_AT', 'EXPIRES_AT', 'PAID_AT', 'COMPLETED_AT'], 'integer'],
+            [['STATUS'], 'in', 'range' => GuestDeclarationDraftStatus::all()],
+            [['ORDER_SN'], 'string', 'max' => 32],
+            [['ACCESS_TOKEN_HASH'], 'string', 'max' => 64],
+            [['CURRENCY'], 'string', 'max' => 8],
+            [['PAYMENT_REFERENCE'], 'string', 'max' => 128],
+            [['USER_ID'], 'string', 'max' => 32],
+            [['ORDER_SN'], 'unique'],
+            [['ACCESS_TOKEN_HASH'], 'unique'],
+            [['PAYMENT_REFERENCE'], 'unique'],
+        ];
+    }
+
+    public function transitionTo(string $newStatus): bool
+    {
+        if (!GuestDeclarationDraftStatus::canTransition($this->STATUS, $newStatus)) {
+            $this->addError('STATUS', 'Invalid guest declaration draft status transition.');
+            return false;
+        }
+
+        $this->STATUS = $newStatus;
+        return $this->save(false, ['STATUS', 'UPDATED_AT']);
+    }
+
+    public static function claimForProcessing(string $orderSn): bool
+    {
+        return self::updateAll(
+            ['STATUS' => GuestDeclarationDraftStatus::PROCESSING, 'UPDATED_AT' => time()],
+            [
+                'AND',
+                ['ORDER_SN' => $orderSn],
+                ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT],
+                ['>', 'EXPIRES_AT', time()],
+            ]
+        ) === 1;
+    }
+
+    public function accessTokenMatches(string $accessToken): bool
+    {
+        return $accessToken !== '' && hash_equals($this->ACCESS_TOKEN_HASH, hash('sha256', $accessToken));
+    }
+
+    public function isExpired(?int $now = null): bool
+    {
+        return GuestDeclarationDraftStatus::isExpired((int) $this->EXPIRES_AT, $now);
+    }
+
+    public function getPayload(): array
+    {
+        $payload = json_decode($this->PAYLOAD, true);
+        return is_array($payload) ? $payload : [];
+    }
+
+    public function getOrderSnapshot(): array
+    {
+        $snapshot = json_decode($this->ORDER_SNAPSHOT, true);
+        return is_array($snapshot) ? $snapshot : [];
+    }
+}

+ 25 - 0
common/models/ShopGoods.php

@@ -207,6 +207,18 @@ class ShopGoods extends \common\components\ActiveRecord
         ];
     }
 
+    /**
+     * 支付方式
+     * @return array
+     */
+    public static function payTypesNoLogin(){
+        return [
+            'pay_stack' => [
+                'name' => 'PayStack'
+            ],
+        ];
+    }
+
     // 获取商品类型
     public static function getGiftType() {
         return [
@@ -240,6 +252,19 @@ class ShopGoods extends \common\components\ActiveRecord
         ];
     }
 
+    // 获取分类类型
+    public static function getCategoryTypeNoLogin() {
+        return [
+            [
+                'id' => 1,
+                'name' => \Yii::t('ctx', 'shopListStandardProducts'),//普通商品
+                'sell_type' => [
+                    self::SALE_TYPE[7],
+                ]
+            ],
+        ];
+    }
+
     public static function getSaleType(): array
     {
         return array_map(function ($item) {

+ 2 - 2
common/models/UserNetwork.php

@@ -388,8 +388,8 @@ class UserNetwork extends \common\components\ActiveRecord
         $db = $table['db'];
         $tableName = $table['tableName'];
         $userNetInfo = $db->createCommand("SELECT LOCATION_TAG,TOP_DEEP FROM {$tableName} WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
-        $userDeep = $userNetInfo['TOP_DEEP'];
-        $userLocationTag = $userNetInfo['LOCATION_TAG'];
+        $userDeep = $userNetInfo['TOP_DEEP']??0;
+        $userLocationTag = $userNetInfo['LOCATION_TAG']??'';
         $totalCountSql = "SELECT COUNT(ID) AS TOTAL_COUNT FROM {$tableName} WHERE LOCATION_TAG LIKE :LOCATION_TAG AND TOP_DEEP<=:TOP_DEEP AND INSTR(`PARENT_UIDS`,'{$userId}')>0  ORDER BY {$orderBy}";
         $totalCount = $db->createCommand($totalCountSql)->bindValues([':LOCATION_TAG'=>$userLocationTag . '%', ':TOP_DEEP'=>$userDeep + $deep])->queryOne();
         $count = $totalCount['TOTAL_COUNT'];

+ 19 - 7
common/models/forms/ApproachDeclarationForm.php

@@ -80,6 +80,9 @@ class ApproachDeclarationForm extends Model
     private $_standardAmount;
     private $_decAmountStandard;
     public $period;
+    /** Set only by the verified guest payment finalizer. */
+    public $isGuestDeclaration = false;
+    public $guestOrderSn;
 
     // 批量报单时添加会员的REDIS里面缓存的添加的会员资料
     const REDIS_WAIT_ADD_USER = 'user:dec:waitAdd';
@@ -619,7 +622,10 @@ class ApproachDeclarationForm extends Model
                 }
 
                 // 报单中心汇率
-                $userInfo = User::findOne(\Yii::$app->user->id);
+                $userInfo = $this->isGuestDeclaration ? User::findOne($this->_decId) : User::findOne(\Yii::$app->user->id);
+                if (!$userInfo) {
+                    throw new Exception(Yii::t('app', 'stockistDoesNotExist'));
+                }
                 $decCountryId = $userInfo->COUNTRY_ID;
                 $decCountry = Countries::getById($decCountryId);
                 $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
@@ -726,6 +732,7 @@ class ApproachDeclarationForm extends Model
                 return $decResult;
             } catch (\Exception $e) {
 //                throw new Exception(Form::formatErrorsForApi($e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage()));
+//                var_dump($e->getTrace());die();
                 throw new Exception(Form::formatErrorsForApi($e->getMessage() . ', ' . $e->getFile() . '(' . $e->getLine() . ')'));
             }
         }
@@ -744,8 +751,8 @@ class ApproachDeclarationForm extends Model
         // 增加会员
         $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->PASSWORD_HASH = $this->isGuestDeclaration ? $this->password : \Yii::$app->security->generatePasswordHash($this->password);
+        $user->PAY_PASSWORD = $this->isGuestDeclaration ? $this->payPassword : \Yii::$app->security->generatePasswordHash($this->payPassword);
         $user->NATION = 0;
         $user->REAL_NAME = $this->realName;
         $user->ID_CARD = $this->mobile;
@@ -818,13 +825,16 @@ class ApproachDeclarationForm extends Model
         $nowPeriodNum = $this->period ?: $periodObj->getNowPeriodNum();
         $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
 
-        $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
+        $ord = $this->isGuestDeclaration && $this->guestOrderSn
+            ? substr($this->guestOrderSn, 2)
+            : 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->scenario = $this->isGuestDeclaration ? 'guestDeclaration' : $decOrderModel->scenario;
+        $decOrderModel->USER_ID = $this->isGuestDeclaration ? 'guestDeclaration' : \Yii::$app->user->id;
         $decOrderModel->TO_USER_ID = $this->_insertUserId;
         $decOrderModel->DEC_AMOUNT = $this->_decAmount;
         $decOrderModel->DEC_PV = $this->_decPv;
@@ -858,7 +868,9 @@ class ApproachDeclarationForm extends Model
         $userCountry = Countries::getById($userCountryId);
         $userCurrencyRate = CurrencyConversions::getToUSDRate($userCountry['LOCAL_CURRENCY_ID']);
         // 报单中心汇率
-        $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+        $decCountryId = $this->isGuestDeclaration
+            ? User::getEnCodeInfo($this->_decId)['COUNTRY_ID']
+            : User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
         $decCountry = Countries::getById($decCountryId);
         $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
 
@@ -889,7 +901,7 @@ class ApproachDeclarationForm extends Model
         $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->CREATE_USER = $this->isGuestDeclaration ? 'guest' : Info::getUserNameByUserId(\Yii::$app->user->id);
         $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
         $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
         $orderModel->EXCHANGE_RATE = $userCurrencyRate;

+ 5 - 2
common/models/forms/ApproachDeclarationLoopForm.php

@@ -19,6 +19,8 @@ use common\models\ShopGoods;
 class ApproachDeclarationLoopForm extends Model
 {
     public $data;
+    public $isGuestDeclaration = false;
+    public $guestOrderSn;
 
     /**
      * @inheritdoc
@@ -118,6 +120,8 @@ class ApproachDeclarationLoopForm extends Model
             $zcUserIdCard = null;
             $model = new ApproachDeclarationForm();
             $model->scenario = $this->scenario;
+            $model->isGuestDeclaration = $this->isGuestDeclaration;
+            $model->guestOrderSn = $this->guestOrderSn;
             $model->allData = $this->data;
             foreach ($this->data as $value) {
                 // 套餐报单
@@ -205,9 +209,8 @@ class ApproachDeclarationLoopForm extends Model
                             $zcUserIdCard = $model->insertUserIdCard;
                         }
                     }
-
                     $result = $model->add($this->data);
-                    
+
                     if(!$result){
                         throw new Exception(Form::formatErrorsForApi($model->getErrors()));
                     }

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

@@ -166,7 +166,10 @@ class ApproachOrderForm extends Model
         }
 
         if ($this->scenario == 'verifyPayStack'){
-            if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
+            if (!in_array((int) $this->_model->STATUS, [
+                (int) \Yii::$app->params['orderStatus']['notPaid']['value'],
+                (int) \Yii::$app->params['orderStatus']['failPaid']['value'],
+            ], true)) {
                 $this->addError('sn', Yii::t('app', 'payTypeError'));
                 return false;
             }
@@ -304,7 +307,7 @@ class ApproachOrderForm extends Model
         }
 
         // 调用PayStack支付校验
-        LoggerTool::info([$this->note['reference'], $this->note]);
+        LoggerTool::info(['paystack_reference' => $this->note['reference'] ?? '']);
 //        $payload = PayStack::transactionVerify($this->note['reference']);
 //        LoggerTool::info($payload);
 //        if ($payload['status'] !== true) {
@@ -320,6 +323,16 @@ class ApproachOrderForm extends Model
         $db = \Yii::$app->db;
         $transaction = $db->beginTransaction();
         try {
+            if ((string) $this->status !== (string) \Yii::$app->params['orderStatus']['paid']['value']) {
+                $this->_model->STATUS = $this->status;
+                $this->_model->NOTE = json_encode($this->note);
+                if (!$this->_model->save()) {
+                    throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
+                }
+                $transaction->commit();
+                return $this->_model;
+            }
+
             // 更新准订单状态为已支付
             $this->_model->STATUS = $this->status;
             $this->_model->NOTE = json_encode($this->note);
@@ -347,17 +360,21 @@ class ApproachOrderForm extends Model
             }
 
             // 会员报单、BA升级
-            if (in_array($orderType, ['userDec', 'baUpgrade', 'userUpgrade'])) {
+            if (in_array($orderType, ['userDec', 'guestUserDec', 'baUpgrade', 'userUpgrade'])) {
                 // 同步报单
                 $approachDecOrder = ApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
                 if ($approachDecOrder) {
                     unset($approachDecOrder['STATUS']);
+                    if ($orderType === 'guestUserDec') {
+                        // USER_ID is the report owner in the permanent record; the payer is never stored.
+                        $approachDecOrder['USER_ID'] = $approachDecOrder['TO_USER_ID'];
+                    }
 
                     // 同步报单
                     DecOrder::insertOne($approachDecOrder);
 
                     // 修改会员锁定状态
-                    if (in_array($orderType, ['userDec', 'baUpgrade'])) {
+                    if (in_array($orderType, ['userDec', 'guestUserDec', 'baUpgrade'])) {
                         if (!User::updateAll(['STATUS' => 1], 'ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']])) {
                             throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'changeUserStatusError')));
                         }

+ 29 - 17
common/models/forms/ApproachReconsumeOrderForm.php

@@ -56,6 +56,7 @@ class ApproachReconsumeOrderForm extends Model
 
     public $userName;
     public $decUserName;
+    public $noLoginUserId;
     public $consignee;
     public $acceptMobile;
     public $province;
@@ -95,7 +96,8 @@ class ApproachReconsumeOrderForm extends Model
     {
         return [
             [['sn', 'expressCompany', 'orderTrackNo', 'status','type','remark','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email'], 'trim'],
-            [['sn', 'expressCompany', 'orderTrackNo', 'status','type','remark','addressId','payType','goodsId','goodsNum', 'payPassword','consignee','acceptMobile','province','city','county','detailaddress'/*,'email'*/,'decUserName'], 'required'],
+            [['sn', 'expressCompany', 'orderTrackNo', 'status','type','remark','addressId','payType','goodsId','goodsNum','consignee','acceptMobile','province','city','county','detailaddress'/*,'email'*/,'decUserName'], 'required'],
+            [['payPassword'], 'required', 'when' => function ($model) { return $model->scenario !== 'noLoginReconsumeOrder'; }],
             [['status'], 'isStatus'],
             [['addressId'], 'isAddress'],
             [['payType'], 'isPayType'],
@@ -145,6 +147,7 @@ class ApproachReconsumeOrderForm extends Model
             'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'payPassword'],
             // 帮会员复消下单
             'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress','decUserName'],
+            'noLoginReconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark','consignee','acceptMobile','province','cityName','lgaName','detailaddress','decUserName'],
         ];
         return array_merge($parentScenarios, $customScenarios);
     }
@@ -409,6 +412,11 @@ class ApproachReconsumeOrderForm extends Model
      * @throws Exception
      * @throws \yii\db\Exception
      */
+    private function getReconsumeActorId()
+    {
+        return $this->scenario === 'noLoginReconsumeOrder' ? $this->noLoginUserId : \Yii::$app->user->id;
+    }
+
     public function add(){
         if(!$this->validate()){
             return null;
@@ -432,16 +440,17 @@ class ApproachReconsumeOrderForm extends Model
         }
 
         // 报单中心汇率
-        $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+        $reconsumeActorId = $this->getReconsumeActorId();
+        $decCountryId = User::getEnCodeInfo($reconsumeActorId)['COUNTRY_ID'];
         $decCountry = Countries::getById($decCountryId);
         $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
         // 会员汇率
         $country = Countries::getById($user['COUNTRY_ID']);
         $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
         //判断是否是报单中心
-        $loginUser = User::getEnCodeInfo(\Yii::$app->user->id);
+        $loginUser = User::getEnCodeInfo($reconsumeActorId);
         if($loginUser['IS_DEC'] == 1){
-            if($decUserID != \Yii::$app->user->id){
+            if($decUserID != $reconsumeActorId){
                 throw new Exception(Yii::t('app', 'decUserNameIsWrong'));
             }
         }
@@ -450,26 +459,29 @@ class ApproachReconsumeOrderForm extends Model
             if ($v) {
                 $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
                 if (!$goods) {
-                    throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                    throw new Exception(Yii::t('app', 'productsDoesSoldOut').'1');
                 }
                 $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
                     [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
                 if (!$goodsNature) {
-                    throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                    throw new Exception(Yii::t('app', 'productsDoesSoldOut').'2');
                 }
 
                 // 汇率
                 $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
+                $basePrice = $this->scenario === 'noLoginReconsumeOrder'
+                    ? $goodsNature['MARKET_PRICE']
+                    : $goodsNature['SELL_PRICE'];
 
                 if($goods['STORE_NUMS']>0){
                     if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
                         $discount = $goodsType[$goods['TYPE']]['discount'];
-                        $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
+                        $realPrice = $basePrice * $discount/100;
                         $realPv = $goods['PRICE_PV'] * $discount/100;
                         $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
                     } else {
                         $discount = $goods['SELL_DISCOUNT'];
-                        $realPrice = $goodsNature['SELL_PRICE'] * $discount;
+                        $realPrice = $basePrice * $discount;
                         $realPv = $goods['PRICE_PV'] * $discount;
                         $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
                     }
@@ -484,7 +496,7 @@ class ApproachReconsumeOrderForm extends Model
 
                     $this->_orderGoods[] = [
                         'GOODS_ID' => $goods['ID'],
-                        'PRICE' => $goodsNature['SELL_PRICE'],
+                        'PRICE' => $basePrice,
                         'PV' => $this->payType == 'prp' ? 0 : $currentPv, // $goods['PRICE_PV'],
                         'REAL_PRICE' => $realPrice,
                         'REAL_PV' => $this->payType == 'prp' ? 0 : $realPv,
@@ -546,7 +558,7 @@ class ApproachReconsumeOrderForm extends Model
 
         $this->_decAmount = $totalAmount;
         $this->_decPv = $this->payType == 'prp' ? 0 : $totalPv;
-        $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
+        $this->_freight = $this->noLoginUserId ? 0 : (($totalAmount >= $freeShipping) ? 0 : $freight);
         $this->_payAmount = $this->_decAmount + $this->_freight;
         $this->_decAmountStandard = $totalAmountStandard;
         $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
@@ -554,12 +566,12 @@ class ApproachReconsumeOrderForm extends Model
         $db = \Yii::$app->db;
         $transaction = $db->beginTransaction();
         try {
-            $loginUserId = \Yii::$app->user->id;
+            $loginUserId = $reconsumeActorId;
 
             //写入订单
-            if (!$orderResult = $this->addOrder()) {
-                throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
-            }
+//            if (!$orderResult = $this->addOrder()) {
+//                throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
+//            }
 
             //是否开启伞下会员限制
             // $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
@@ -575,7 +587,7 @@ class ApproachReconsumeOrderForm extends Model
                 if ($v){
                     $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
                     if (!$goods) {
-                        throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                        throw new Exception(Yii::t('app', 'productsDoesSoldOut').'3');
                     }
                     if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
                         $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
@@ -634,7 +646,7 @@ class ApproachReconsumeOrderForm extends Model
         $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
 
         //帮复消会员Id(登陆会员)
-        $loginUserId = \Yii::$app->user->id;
+        $loginUserId = $this->getReconsumeActorId();
         $loginUserName = Info::getUserNameByUserId($loginUserId);
         //订单会员Id
         $userId = Info::getUserIdByUserName($this->userName);
@@ -670,7 +682,7 @@ class ApproachReconsumeOrderForm extends Model
         $orderModel->ADDRESS = $this->detailaddress;
         $orderModel->FRONT_REMARK = $this->remark;
         $orderModel->WAREHOUSE = $warehouse;
-        $orderModel->STATUS = 1;
+        $orderModel->STATUS = $this->payType == 'pay_stack'?0:1;
         $orderModel->CREATED_AT = Date::nowTime();
         $orderModel->CREATE_USER = $loginUserName;
         $orderModel->EMAIL = $email ?? '';

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

@@ -245,7 +245,7 @@ class UserForm extends Model
         // 获取排序为2的报单级别
         $decLevel = DeclarationLevel::getLevelFromSort(1);
         if($this->zcPv < $decLevel['PERF']){
-            if($this->allData['hasInstalment'] && $this->zcPv + 30 >= $decLevel['PERF']){
+            if(!empty($this->allData['hasInstalment']) && $this->zcPv + 30 >= $decLevel['PERF']){
             }else{
                 $this->addError($attribute, '注册'.$this->userName.'时,注册PV低于最低级别要求,不能报首购单');
             }
@@ -261,7 +261,7 @@ class UserForm extends Model
         $otherUser = User::find()->where("ID_CARD=:ID_CARD AND ID<>:ID AND IS_UNION=0 AND DELETED=0 AND (ID_CARD_PREFIX IS NULL OR ID_CARD_PREFIX='')", [':ID_CARD'=>$this->idCard, ':ID'=>$this->userId])->select('ID')->asArray()->all();
         // 拿到所有的批量报单数据
         foreach($this->allData as $decData){
-            if($decData['insertUserIdCard'] == $this->idCard){
+            if(($decData['insertUserIdCard'] ?? null) == $this->idCard && !empty($decData['toUserId'])){
                 $otherUser[] = ['ID'=>$decData['toUserId']];
             }
         }

+ 551 - 0
common/services/GuestDeclarationOrderService.php

@@ -0,0 +1,551 @@
+<?php
+
+namespace common\services;
+
+use common\helpers\GuestDeclarationDraftStatus;
+use common\helpers\Cache;
+use common\helpers\Form;
+use common\helpers\user\Info;
+use common\models\Countries;
+use common\models\Currency;
+use common\models\GuestDeclarationDraft;
+use common\models\ApproachOrder;
+use common\models\DeclarationPackage;
+use common\models\ShopGoods;
+use common\models\ShopGoodsNature;
+use common\models\Region;
+use common\models\forms\ApproachDeclarationForm;
+use common\models\forms\ApproachDeclarationLoopForm;
+use common\models\forms\ApproachOrderForm;
+use common\models\User;
+use common\models\UserNetwork;
+use common\models\UserRelation;
+use Yii;
+use yii\web\BadRequestHttpException;
+use yii\web\NotFoundHttpException;
+
+/** Handles the public, pre-payment part of a guest registration order. */
+class GuestDeclarationOrderService
+{
+    private const DRAFT_TTL = 86400;
+    private const PAYMENT_INITIALIZATION_TIMEOUT = 0;
+
+    public function createDraft(string $countryId): array
+    {
+        $country = Countries::getById($countryId);
+        if (!$country || empty($country['ACTIVE'])) {
+            throw new BadRequestHttpException('Unsupported country.');
+        }
+        $currency = Currency::getById((string) $country['LOCAL_CURRENCY_ID']);
+        if (!$currency || empty($currency['ACTIVE']) || empty($currency['CODE'])) {
+            throw new BadRequestHttpException('Payment currency is unavailable.');
+        }
+
+        $token = Yii::$app->security->generateRandomString(64);
+        $username = Info::generateWebName($countryId);
+        if (!$username) {
+            throw new \RuntimeException('Unable to generate a member number.');
+        }
+        $draft = new GuestDeclarationDraft();
+        $draft->ID = Yii::$app->security->generateRandomString(32);
+        $draft->ORDER_SN = 'OS' . strtoupper(bin2hex(random_bytes(12)));
+        $draft->ACCESS_TOKEN_HASH = hash('sha256', $token);
+        $draft->STATUS = GuestDeclarationDraftStatus::DRAFT;
+        $draft->PAYLOAD = '{}';
+        $draft->ORDER_SNAPSHOT = '{}';
+        $draft->PAY_AMOUNT = 0;
+        $draft->CURRENCY = strtoupper($currency['CODE']);
+        $draft->CREATED_AT = time();
+        $draft->EXPIRES_AT = time() + self::DRAFT_TTL;
+
+        // This is a proposal only. The number is checked again before payment completion.
+        $draft->USER_ID = null;
+        $draft->PAYLOAD = json_encode([
+            'countryId' => $countryId,
+            'insertUserName' => $username,
+        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+        if (!$draft->save()) {
+            throw new \RuntimeException('Unable to create guest order draft.');
+        }
+        if (!Yii::$app->redis->setnx('key_' . $username, $username)) {
+            $draft->delete();
+            throw new \RuntimeException('Unable to reserve a unique member number. Please retry.');
+        }
+        Yii::$app->redis->expire('key_' . $username, self::DRAFT_TTL + 600);
+
+        return [
+            'draftId' => $draft->ID,
+            'accessToken' => $token,
+            'insertUserName' => $username,
+            'expiresAt' => (int) $draft->EXPIRES_AT,
+            'currency' => $draft->CURRENCY,
+        ];
+    }
+
+    public function getDraftStatus(string $draftId, string $accessToken): array
+    {
+        $draft = $this->loadAuthorizedDraft($draftId, $accessToken);
+        if ($draft->STATUS === GuestDeclarationDraftStatus::PAYMENT_INITIALIZING && (int) $draft->UPDATED_AT < time() - 900) {
+            $draft->transitionTo(GuestDeclarationDraftStatus::MANUAL_REVIEW);
+        } elseif ($draft->isExpired() && in_array($draft->STATUS, [GuestDeclarationDraftStatus::DRAFT, GuestDeclarationDraftStatus::PENDING_PAYMENT], true)) {
+            $draft->transitionTo(GuestDeclarationDraftStatus::EXPIRED);
+        }
+
+        return [
+            'status' => $draft->STATUS,
+            'orderSn' => $draft->STATUS === GuestDeclarationDraftStatus::COMPLETED ? $draft->ORDER_SN : null,
+            'userName' => $draft->STATUS === GuestDeclarationDraftStatus::COMPLETED ? ($draft->getPayload()['insertUserName'] ?? null) : null,
+        ];
+    }
+
+    public function debugCompletePaidDraft(string $draftId, string $accessToken): array
+    {
+//        if (!defined('YII_ENV') || YII_ENV === 'prod') {
+//            throw new NotFoundHttpException();
+//        }
+
+        $draft = $this->loadAuthorizedDraft($draftId, $accessToken);
+        if ($draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT || $draft->isExpired()) {
+            throw new BadRequestHttpException('Only an active pending-payment draft can be debug-completed.');
+        }
+        if (!$draft->PAYMENT_REFERENCE || (float) $draft->PAY_AMOUNT <= 0 || !$draft->CURRENCY) {
+            throw new BadRequestHttpException('The guest draft has no valid initialized payment.');
+        }
+
+        $now = gmdate('Y-m-d\\TH:i:s\\Z');
+        $transaction = [
+            'id' => 'DEBUG-' . $draft->ID,
+            'domain' => 'debug',
+            'status' => 'success',
+            'reference' => $draft->PAYMENT_REFERENCE,
+            'amount' => (int) round((float) $draft->PAY_AMOUNT * 100),
+            'currency' => strtoupper((string) $draft->CURRENCY),
+            'metadata' => ['custom_fields' => [
+                ['display_name' => 'Order SN', 'variable_name' => 'orderSn', 'value' => $draft->ORDER_SN],
+                ['display_name' => 'Order Type', 'variable_name' => 'orderType', 'value' => 'guestUserDec'],
+            ]],
+            'created_at' => $now,
+            'paid_at' => $now,
+            'channel' => 'debug',
+            'email' => (string) ($draft->getPayload()['email'] ?? ''),
+        ];
+
+        return $this->completePaidDraft($draft->ORDER_SN, $transaction);
+    }
+
+    public function submitDraft(string $draftId, string $accessToken, array $input): array
+    {
+        $draft = $this->loadAuthorizedDraft($draftId, $accessToken);
+        if ($draft->isExpired()) {
+            $draft->transitionTo(GuestDeclarationDraftStatus::EXPIRED);
+            throw new BadRequestHttpException('Guest order draft has expired.');
+        }
+        if ($draft->STATUS === GuestDeclarationDraftStatus::PAYMENT_INITIALIZING) {
+            $recoveredStatus = $draft->PAYMENT_REFERENCE
+                ? GuestDeclarationDraftStatus::PENDING_PAYMENT
+                : GuestDeclarationDraftStatus::DRAFT;
+            GuestDeclarationDraft::updateAll(
+                ['STATUS' => $recoveredStatus, 'UPDATED_AT' => time()],
+                [
+                    'AND',
+                    ['ID' => $draft->ID],
+                    ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_INITIALIZING],
+                    ['<' , 'UPDATED_AT', time() - self::PAYMENT_INITIALIZATION_TIMEOUT],
+                ]
+            );
+            $draft->refresh();
+            if ($draft->STATUS === GuestDeclarationDraftStatus::PAYMENT_INITIALIZING) {
+                throw new BadRequestHttpException('Payment initialization is in progress.');
+            }
+        }
+        if (!in_array($draft->STATUS, [GuestDeclarationDraftStatus::DRAFT, GuestDeclarationDraftStatus::PAYMENT_FAILED, GuestDeclarationDraftStatus::PENDING_PAYMENT], true)) {
+            throw new BadRequestHttpException('Guest order draft cannot be submitted in its current state.');
+        }
+
+        foreach (['amount', 'payAmount', 'currency', 'pv', 'exchangeRate', 'goodsTitle', 'price', 'realPrice'] as $untrustedField) {
+            if (array_key_exists($untrustedField, $input)) {
+                throw new BadRequestHttpException('Price and product fields are calculated by the server.');
+            }
+        }
+
+        $payload = $draft->getPayload();
+        $countryId = (string) ($payload['countryId'] ?? '');
+        unset($input['draftId'], $input['accessToken'], $input['allData'], $input['isGuestDeclaration'], $input['guestOrderSn'], $input['_insertUserId']);
+        $input['insertUserName'] = $payload['insertUserName'] ?? '';
+        $input['countryId'] = $countryId;
+        $input['goodsId'] = $input['goodsId'] ?? [];
+        $input['goodsNum'] = $input['goodsNum'] ?? [];
+        $input['type'] = ApproachDeclarationForm::TYPE_ZC;
+        $input['payType'] = 'pay_stack';
+        $input['province'] = !empty($input['province']) ? $input['province'] : 1;
+        $input['city'] = !empty($input['city']) ? $input['city'] : 1;
+        $input['county'] = !empty($input['county']) ? $input['county'] : 1;
+        $referrerName = trim((string) ($input['conUserName'] ?? ''));
+        $sponsorName = trim((string) ($input['recUserName'] ?? ''));
+        $referrerId = Info::getUserIdByUserName($referrerName);
+        $sponsorId = Info::getUserIdByUserName($sponsorName);
+        $relation = $referrerId ? UserRelation::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $referrerId]) : null;
+        $parentIds = $relation ? array_map('strval', explode(',', (string) $relation['PARENT_UIDS'])) : [];
+        if (!$referrerId || !$sponsorId || ((string) $sponsorId !== (string) $referrerId && !in_array((string) $sponsorId, $parentIds, true))) {
+            throw new BadRequestHttpException(Yii::t('app', 'fillSponsorUpline'));
+        }
+        $stockistName = trim((string) ($input['decUserName'] ?? ''));
+        if ($stockistName === '' || !User::find()->where(['USER_NAME' => $stockistName, 'IS_DEC' => 1])->exists()) {
+            throw new BadRequestHttpException(Yii::t('app', 'stockistDoesNotExist'));
+        }
+        if ((string) $input['province'] !== '1' && !Region::getWarehouseByCode($input['province'])) {
+            throw new BadRequestHttpException(Yii::t('app', 'deliveryTemporarilyNotSupported'));
+        }
+        $bottomPlace = UserNetwork::getBottomPlace($referrerId, '', 'left');
+        $bottom = UserNetwork::find()->select('USER_ID')->where(['LOCATION_TAG' => $bottomPlace])->asArray()->one();
+        $bottomUser = $bottom ? User::findOneAsArray(['ID' => $bottom['USER_ID']], [], 'USER_NAME') : null;
+        if (!$bottomUser) {
+            throw new BadRequestHttpException(Yii::t('app', 'stockistDoesNotExist'));
+        }
+        $input['conUserName'] = $bottomUser['USER_NAME'];
+        $input['recUserName'] = $referrerName;
+        $input['bottomUserName'] = $sponsorName;
+        $input['location'] = 1;
+
+        $form = new ApproachDeclarationForm();
+        $form->scenario = 'userDec';
+        $explicitlyAllowedAttributes = [
+            'bottomUserName', 'payType', 'countryId', 'packageId', 'goodsId', 'goodsNum',
+            'email', 'languageId',
+        ];
+        $allowedNames = array_unique(array_merge($form->safeAttributes(), $explicitlyAllowedAttributes));
+        $allowedInput = array_flip($allowedNames);
+        unset($allowedInput['allData']);
+        $input = array_intersect_key($input, $allowedInput);
+        foreach ($input as $name => $value) {
+            if (in_array($name, $allowedNames, true)) {
+                $form->$name = $value;
+            }
+        }
+        $form->bottomUserName = $sponsorName;
+        $form->allData = [$input];
+        if (!$form->validate()) {
+            throw new BadRequestHttpException(Form::formatErrorsForApi($form->getErrors()));
+        }
+        if (User::find()->where(['USER_NAME' => $input['insertUserName']])->exists()
+            || Yii::$app->redis->get('key_' . $input['insertUserName']) !== $input['insertUserName']
+        ) {
+            throw new BadRequestHttpException(Yii::t('app', 'memberNumberExpired'));
+        }
+
+        [$amount, $pv, $goods] = $this->quote($input);
+        $levels = Cache::getDecLevelConfig();
+        $minimumPv = $levels ? min(array_map(static function ($level) { return (float) $level['PERF']; }, $levels)) : 0;
+        if ($pv < $minimumPv) {
+            throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanSelectedBV').'1');
+        }
+        if ((string) ($input['decWay'] ?? '') !== '1') {
+            $selectedLevel = $levels[$input['decLv'] ?? ''] ?? null;
+            if (!$selectedLevel) {
+                throw new BadRequestHttpException(Yii::t('app', 'pleaseSelectTheEntryLevel'));
+            }
+            if ($pv < (float) $selectedLevel['PERF']) {
+                throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanSelectedBV').'2');
+            }
+            $actualLevel = null;
+            foreach ($levels as $levelId => $level) {
+                if ($pv >= (float) $level['PERF']) {
+                    $actualLevel = $levelId;
+                }
+            }
+            if ($actualLevel !== null && (string) $input['decLv'] !== (string) $actualLevel) {
+                throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanNextSelectedLevelBV').'3');
+            }
+        }
+        if ($amount <= 0 || empty($input['email']) || !filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
+            throw new BadRequestHttpException('A valid payment email and positive order amount are required.');
+        }
+        $country = Countries::getById($countryId);
+        $currency = Currency::getById((string) 104);
+        $orderSn = $draft->ORDER_SN;
+        $input['password'] = Yii::$app->security->generatePasswordHash((string) $input['password']);
+        $input['payPassword'] = Yii::$app->security->generatePasswordHash((string) $input['payPassword']);
+        $storedPayload = json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+        $previousStatus = $draft->STATUS;
+        $reserved = GuestDeclarationDraft::updateAll(
+            ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_INITIALIZING, 'UPDATED_AT' => time()],
+            ['AND', ['ID' => $draft->ID], ['STATUS' => $previousStatus], ['>' , 'EXPIRES_AT', time()]]
+        );
+        if ($reserved !== 1) {
+            $draft->refresh();
+            if ($draft->STATUS === GuestDeclarationDraftStatus::PENDING_PAYMENT) {
+                return $this->paymentResponse($draft);
+            }
+            throw new BadRequestHttpException('Guest order draft is already being submitted.');
+        }
+        $draft->refresh();
+        $paymentReference = 'GD' . strtoupper(bin2hex(random_bytes(12)));
+        $init = \common\helpers\PayStack::transactionInit(
+            strtoupper($currency['CODE']),
+            $amount,
+            $input['email'],
+            ['custom_fields' => [
+                ['display_name' => 'Order SN', 'variable_name' => 'orderSn', 'value' => $orderSn],
+                ['display_name' => 'Order Type', 'variable_name' => 'orderType', 'value' => 'guestUserDec'],
+            ]],
+            $paymentReference
+        );
+        if (empty($init['status']) || empty($init['data']['reference']) || empty($init['data']['authorization_url'])) {
+            GuestDeclarationDraft::updateAll(
+                ['STATUS' => $previousStatus, 'UPDATED_AT' => time()],
+                ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_INITIALIZING]]
+            );
+            throw new \RuntimeException('Unable to initialize payment. Please retry.');
+        }
+
+        $draft->PAYLOAD = $storedPayload;
+        $draft->ORDER_SNAPSHOT = json_encode(['amount' => $amount, 'pv' => $pv, 'goods' => $goods], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+        $draft->PAY_AMOUNT = $amount;
+        $draft->CURRENCY = strtoupper($currency['CODE']);
+        $draft->PAYMENT_REFERENCE = $init['data']['reference'];
+        $draft->PAYMENT_NOTE = json_encode([
+            'authorization_url' => $init['data']['authorization_url'],
+            'access_code' => $init['data']['access_code'] ?? null,
+        ]);
+        $draft->STATUS = GuestDeclarationDraftStatus::PENDING_PAYMENT;
+        $draft->UPDATED_AT = time();
+        if (!$draft->save(false)) {
+            GuestDeclarationDraft::updateAll([
+                'STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW,
+                'PAYLOAD' => $draft->PAYLOAD,
+                'ORDER_SNAPSHOT' => $draft->ORDER_SNAPSHOT,
+                'PAY_AMOUNT' => $draft->PAY_AMOUNT,
+                'CURRENCY' => $draft->CURRENCY,
+                'PAYMENT_REFERENCE' => $draft->PAYMENT_REFERENCE,
+                'PAYMENT_NOTE' => $draft->PAYMENT_NOTE,
+                'UPDATED_AT' => time(),
+            ], ['ID' => $draft->ID]);
+            throw new \RuntimeException('Payment started but its draft could not be saved; manual review is required.');
+        }
+        return $this->paymentResponse($draft);
+    }
+
+    private function paymentResponse(GuestDeclarationDraft $draft): array
+    {
+        $payment = json_decode((string) $draft->PAYMENT_NOTE, true) ?: [];
+        return [
+            'orderSn' => $draft->ORDER_SN,
+            'amount' => (float) $draft->PAY_AMOUNT,
+            'currency' => $draft->CURRENCY,
+            'reference' => $draft->PAYMENT_REFERENCE,
+            'authorizationUrl' => $payment['authorization_url'] ?? null,
+            'accessCode' => $payment['access_code'] ?? null,
+        ];
+    }
+
+    private function quote(array $input): array
+    {
+        $goods = [];
+        $amount = 0.0;
+        $pv = 0.0;
+        if (!empty($input['decWay']) && (string) $input['decWay'] === '1') {
+            $package = DeclarationPackage::findOneAsArray('ID=:ID AND STATUS=1', [':ID' => $input['packageId'] ?? null]);
+            if (!$package || (int) $package['STORE_NUMS'] <= 0) {
+                throw new BadRequestHttpException(Yii::t('app', 'productsDoesSoldOut'));
+            }
+            if ((string) ($input['decLv'] ?? '') !== (string) $package['LEVEL_ID']) {
+                throw new BadRequestHttpException(Yii::t('app', 'pleaseSelectTheEntryLevel'));
+            }
+            $amount = (float) $package['AMOUNT'];
+            $pv = (float) $package['PV'];
+            $goods[] = ['GOODS_ID' => $package['ID'], 'PRICE' => $amount, 'PV' => $pv, 'BUY_NUMS' => 1, 'SKU_CODE' => $package['PACKAGE_NO'], 'GOODS_TITLE' => $package['PACKAGE_NAME']];
+        } else {
+            $ids = $input['goodsId'] ?? [];
+            $quantities = $input['goodsNum'] ?? [];
+            if (!is_array($ids) || !is_array($quantities) || count($ids) !== count($quantities) || !$ids) {
+                throw new BadRequestHttpException('Select at least one valid product.');
+            }
+            foreach ($ids as $index => $id) {
+                $quantity = filter_var($quantities[$index], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 99]]);
+                if ($quantity === false) {
+                    throw new BadRequestHttpException('Product quantity is invalid.');
+                }
+                if ($quantity === 0) {
+                    continue;
+                }
+                $product = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID' => $id]);
+                $nature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID', [':GOODS_ID' => $id, ':COUNTRY_ID' => $input['countryId']]);
+                if (!$product || !$nature || (int) $product['STORE_NUMS'] < $quantity || !empty($product['INSTALMENT'])) {
+                    throw new BadRequestHttpException(Yii::t('app', 'productsDoesSoldOut'));
+                }
+                $unitPrice = (float) $nature['MARKET_PRICE'];
+                $unitPv = (float) $product['PRICE_PV'];
+                $amount += $unitPrice * $quantity;
+                $pv += $unitPv * $quantity;
+                $goods[] = ['GOODS_ID' => $product['ID'], 'PRICE' => $unitPrice, 'PV' => $unitPv, 'BUY_NUMS' => $quantity, 'SKU_CODE' => $product['GOODS_NO'], 'GOODS_TITLE' => $product['GOODS_NAME']];
+            }
+            if (!$goods) {
+                throw new BadRequestHttpException('Select at least one valid product.2');
+            }
+        }
+        return [$amount, $pv, $goods];
+    }
+
+    public function completePaidDraft(string $orderSn, array $verifiedTransaction): array
+    {
+        $draft = GuestDeclarationDraft::findOne(['ORDER_SN' => $orderSn]);
+        if (!$draft) {
+            throw new NotFoundHttpException('Guest order draft was not found.');
+        }
+        if ($draft->STATUS === GuestDeclarationDraftStatus::COMPLETED) {
+            return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
+        }
+        if ($draft->STATUS === GuestDeclarationDraftStatus::MANUAL_REVIEW) {
+            return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
+        }
+        $fields = $verifiedTransaction['metadata']['custom_fields'] ?? [];
+        $metadataMatches = ($fields[0]['value'] ?? null) === $draft->ORDER_SN
+            && ($fields[1]['value'] ?? null) === 'guestUserDec';
+        if ($draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
+            && ($verifiedTransaction['status'] ?? null) === 'success'
+            && $metadataMatches
+        ) {
+            GuestDeclarationDraft::updateAll(
+                ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
+                ['ID' => $draft->ID]
+            );
+            return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
+        }
+        $expectedAmount = (int) round(((float) $draft->PAY_AMOUNT) * 100);
+        if ($draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
+            || ($verifiedTransaction['status'] ?? null) !== 'success'
+            || (string) ($verifiedTransaction['reference'] ?? '') !== (string) $draft->PAYMENT_REFERENCE
+            || (int) ($verifiedTransaction['amount'] ?? -1) !== $expectedAmount
+            || strtoupper((string) ($verifiedTransaction['currency'] ?? '')) !== strtoupper((string) $draft->CURRENCY)
+        ) {
+            if (($verifiedTransaction['reference'] ?? null) === $draft->PAYMENT_REFERENCE || $metadataMatches) {
+                GuestDeclarationDraft::updateAll(
+                    ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
+                    ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
+                );
+                return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
+            }
+            throw new BadRequestHttpException('Verified payment does not match this guest order.');
+        }
+        if (!$metadataMatches) {
+            GuestDeclarationDraft::updateAll(
+                ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
+                ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
+            );
+            return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
+        }
+        if ($draft->isExpired()) {
+            GuestDeclarationDraft::updateAll(
+                ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
+                ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
+            );
+            return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
+        }
+
+        $transaction = Yii::$app->db->beginTransaction();
+        $claimed = false;
+        try {
+            if (!GuestDeclarationDraft::claimForProcessing($orderSn)) {
+                $draft->refresh();
+                if ($draft->STATUS === GuestDeclarationDraftStatus::COMPLETED) {
+                    $transaction->commit();
+                    return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
+                }
+                throw new \RuntimeException('Guest order is already being processed.');
+            }
+            $claimed = true;
+            $draft->refresh();
+            $payload = $draft->getPayload();
+            $snapshot = $draft->getOrderSnapshot();
+            $loop = new ApproachDeclarationLoopForm();
+            $loop->scenario = 'userDec';
+            $loop->isGuestDeclaration = true;
+            $loop->guestOrderSn = $orderSn;
+            $loop->data = [$payload];
+            $approachOrder = $loop->add();
+            if (!$approachOrder instanceof ApproachOrder) {
+                throw new \RuntimeException('Unable to create the paid registration order.');
+            }
+            if (abs((float) $approachOrder->ORDER_AMOUNT - (float) $snapshot['amount']) > 0.000001
+                || abs((float) $approachOrder->PV - (float) $snapshot['pv']) > 0.000001
+            ) {
+                throw new \RuntimeException('Order price changed after payment; manual review is required.');
+            }
+            if (isset($approachOrder->USER_NAME) && $approachOrder->USER_NAME !== $payload['insertUserName']) {
+                throw new \RuntimeException('Created member does not match the guest order.');
+            }
+
+            $verify = new ApproachOrderForm();
+            $verify->scenario = 'verifyPayStack';
+            $verify->sn = $orderSn;
+            $verify->status = Yii::$app->params['orderStatus']['paid']['value'];
+            $verify->note = [
+                'id' => $verifiedTransaction['id'] ?? null,
+                'domain' => $verifiedTransaction['domain'] ?? null,
+                'status' => $verifiedTransaction['status'],
+                'reference' => $verifiedTransaction['reference'],
+                'amount' => $verifiedTransaction['amount'],
+                'created_at' => $verifiedTransaction['created_at'] ?? null,
+                'paid_at' => $verifiedTransaction['paid_at'] ?? null,
+                'channel' => $verifiedTransaction['channel'] ?? null,
+                'currency' => $verifiedTransaction['currency'],
+                'metadata' => $verifiedTransaction['metadata'],
+                'email' => $verifiedTransaction['customer']['email'] ?? $verifiedTransaction['email'] ?? '',
+            ];
+            $verifiedOrder = $verify->verifyPayStack();
+            if (!$verifiedOrder) {
+                throw new \RuntimeException('Unable to finalize the paid registration order.');
+            }
+
+            $draft->USER_ID = $approachOrder->USER_ID;
+            $draft->PAYLOAD = json_encode(['insertUserName' => $payload['insertUserName']], JSON_UNESCAPED_UNICODE);
+        $draft->STATUS = GuestDeclarationDraftStatus::COMPLETED;
+            $draft->PAID_AT = time();
+            $draft->COMPLETED_AT = time();
+            $draft->UPDATED_AT = time();
+            if (!$draft->save(false)) {
+                throw new \RuntimeException('Unable to complete guest order draft.');
+            }
+            $transaction->commit();
+            return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
+        } catch (\Throwable $e) {
+            if ($transaction->isActive) {
+                $transaction->rollBack();
+            }
+            if ($claimed) {
+                GuestDeclarationDraft::updateAll(
+                    ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
+                    ['AND', ['ORDER_SN' => $orderSn], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
+                );
+            }
+            throw $e;
+        }
+    }
+
+    public function markPaymentFailed(string $reference, array $verifiedTransaction): void
+    {
+        $draft = GuestDeclarationDraft::findOne(['PAYMENT_REFERENCE' => $reference]);
+        if (!$draft || $draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
+            || ($verifiedTransaction['status'] ?? null) === 'success'
+            || (string) ($verifiedTransaction['reference'] ?? '') !== $reference
+        ) {
+            return;
+        }
+        GuestDeclarationDraft::updateAll(
+            ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_FAILED, 'PAYMENT_REFERENCE' => null, 'PAYMENT_NOTE' => null, 'UPDATED_AT' => time()],
+            ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT], ['PAYMENT_REFERENCE' => $reference]]
+        );
+    }
+
+    /**
+     * Require both unguessable draft id and its one-time bearer token.
+     */
+    private function loadAuthorizedDraft(string $draftId, string $accessToken): GuestDeclarationDraft
+    {
+        $draft = GuestDeclarationDraft::findOne(['ID' => $draftId]);
+        if (!$draft || !$draft->accessTokenMatches($accessToken)) {
+            throw new NotFoundHttpException('Guest order draft was not found.');
+        }
+        return $draft;
+    }
+}

+ 29 - 0
common/tests/standalone/guest-declaration-draft-status.php

@@ -0,0 +1,29 @@
+<?php
+
+require __DIR__ . '/../../helpers/GuestDeclarationDraftStatus.php';
+
+use common\helpers\GuestDeclarationDraftStatus;
+
+$checks = [
+    'draft can reserve payment initialization' => GuestDeclarationDraftStatus::canTransition('draft', 'payment_initializing'),
+    'payment initialization can become pending' => GuestDeclarationDraftStatus::canTransition('payment_initializing', 'pending_payment'),
+    'payment initialization can enter manual review' => GuestDeclarationDraftStatus::canTransition('payment_initializing', 'manual_review'),
+    'pending payment can be claimed' => GuestDeclarationDraftStatus::canTransition('pending_payment', 'processing'),
+    'pending payment can be resubmitted with updated details' => GuestDeclarationDraftStatus::canTransition('pending_payment', 'payment_initializing'),
+    'pending payment can enter manual review' => GuestDeclarationDraftStatus::canTransition('pending_payment', 'manual_review'),
+    'failed payment can be retried' => GuestDeclarationDraftStatus::canTransition('payment_failed', 'payment_initializing'),
+    'processing can complete' => GuestDeclarationDraftStatus::canTransition('processing', 'completed'),
+    'completed cannot be reopened' => !GuestDeclarationDraftStatus::canTransition('completed', 'pending_payment'),
+    'pending payment can expire' => GuestDeclarationDraftStatus::isExpired(99, 100),
+    'expiry boundary is expired' => GuestDeclarationDraftStatus::isExpired(100, 100),
+    'future expiry is not expired' => !GuestDeclarationDraftStatus::isExpired(101, 100),
+];
+
+foreach ($checks as $description => $passed) {
+    if (!$passed) {
+        fwrite(STDERR, "FAIL: {$description}\n");
+        exit(1);
+    }
+}
+
+echo 'PASS: ' . count($checks) . " guest draft status checks\n";

+ 24 - 0
common/tests/standalone/paystack-webhook-signature.php

@@ -0,0 +1,24 @@
+<?php
+
+require __DIR__ . '/../../helpers/PayStack.php';
+
+use common\helpers\PayStack;
+
+$body = '{"event":"charge.success","data":{"reference":"OS123"}}';
+$secret = 'standalone-test-secret';
+$signature = hash_hmac('sha512', $body, $secret);
+$checks = [
+    'accepts the matching SHA512 signature' => PayStack::verifyWebhookSignature($body, $signature, $secret),
+    'rejects a different signature' => !PayStack::verifyWebhookSignature($body, str_repeat('0', 128), $secret),
+    'rejects an empty signature' => !PayStack::verifyWebhookSignature($body, '', $secret),
+    'signature binds to the raw request body' => !PayStack::verifyWebhookSignature($body . ' ', $signature, $secret),
+];
+
+foreach ($checks as $description => $passed) {
+    if (!$passed) {
+        fwrite(STDERR, "FAIL: {$description}\n");
+        exit(1);
+    }
+}
+
+echo 'PASS: ' . count($checks) . " PayStack signature checks\n";

+ 2 - 1
console/controllers/ToolController.php

@@ -205,7 +205,8 @@ class ToolController extends BaseController
 
     public function actionSendEmail()
     {
-        Email::sendRegistrationEmail('18511880790@163.com', 'zhangl', 'test123');
+        $result = Email::sendRegistrationEmail('bosiomlee@qq.com', 'zhangl', 'test123');
+        var_dump($result);
     }
 
     public function actionOrderInvoiceRemark()

+ 39 - 0
console/migrations/m261009_000001_create_guest_declaration_draft.php

@@ -0,0 +1,39 @@
+<?php
+
+use yii\db\Migration;
+
+class m261009_000001_create_guest_declaration_draft extends Migration
+{
+    public function safeUp()
+    {
+        $this->createTable('{{%GUEST_DECLARATION_DRAFT}}', [
+            'ID' => $this->string(32)->notNull(),
+            'ORDER_SN' => $this->string(32)->notNull(),
+            'ACCESS_TOKEN_HASH' => $this->string(64)->notNull(),
+            'STATUS' => $this->string(32)->notNull(),
+            'PAYLOAD' => $this->text()->notNull(),
+            'ORDER_SNAPSHOT' => $this->text()->notNull(),
+            'PAY_AMOUNT' => $this->decimal(20, 6)->notNull(),
+            'CURRENCY' => $this->string(8)->notNull(),
+            'PAYMENT_REFERENCE' => $this->string(128),
+            'PAYMENT_NOTE' => $this->text(),
+            'USER_ID' => $this->string(32),
+            'CREATED_AT' => $this->integer()->notNull(),
+            'UPDATED_AT' => $this->integer(),
+            'EXPIRES_AT' => $this->integer()->notNull(),
+            'PAID_AT' => $this->integer(),
+            'COMPLETED_AT' => $this->integer(),
+            'PRIMARY KEY ([[ID]])',
+        ]);
+
+        $this->createIndex('UX_GUEST_DRAFT_ORDER_SN', '{{%GUEST_DECLARATION_DRAFT}}', 'ORDER_SN', true);
+        $this->createIndex('UX_GUEST_DRAFT_TOKEN_HASH', '{{%GUEST_DECLARATION_DRAFT}}', 'ACCESS_TOKEN_HASH', true);
+        $this->createIndex('UX_GUEST_DRAFT_PAYMENT_REF', '{{%GUEST_DECLARATION_DRAFT}}', 'PAYMENT_REFERENCE', true);
+        $this->createIndex('IX_GUEST_DRAFT_STATUS_EXPIRY', '{{%GUEST_DECLARATION_DRAFT}}', ['STATUS', 'EXPIRES_AT']);
+    }
+
+    public function safeDown()
+    {
+        $this->dropTable('{{%GUEST_DECLARATION_DRAFT}}');
+    }
+}

+ 43 - 0
console/migrations/m261009_000002_allow_empty_declaration_payer.php

@@ -0,0 +1,43 @@
+<?php
+
+use yii\db\Migration;
+
+class m261009_000002_allow_empty_declaration_payer extends Migration
+{
+    public function safeUp()
+    {
+        $this->setPayerNullability(false);
+    }
+
+    public function safeDown()
+    {
+        $table = '{{%APPROACH_DEC_ORDER}}';
+        $nullCount = (int) (new \yii\db\Query())
+            ->from($table)
+            ->where(['USER_ID' => null])
+            ->count('*', $this->db);
+        if ($nullCount > 0) {
+            throw new \RuntimeException('Cannot restore APPROACH_DEC_ORDER.USER_ID NOT NULL while guest declaration rows exist.');
+        }
+
+        $this->setPayerNullability(true);
+    }
+
+    private function setPayerNullability(bool $notNull): void
+    {
+        $table = '{{%APPROACH_DEC_ORDER}}';
+        $schema = $this->db->getTableSchema($table, true);
+        if (!$schema || !isset($schema->columns['USER_ID'])) {
+            throw new \RuntimeException('APPROACH_DEC_ORDER.USER_ID column was not found.');
+        }
+
+        $column = $schema->columns['USER_ID'];
+        if ((bool) $column->allowNull === !$notNull) {
+            return;
+        }
+
+        $definition = $this->db->getSchema()->createColumnSchemaBuilder($column->type, $column->size);
+        $definition->notNull($notNull);
+        $this->alterColumn($table, 'USER_ID', $definition);
+    }
+}

+ 11 - 0
frontendApi/config/params.php

@@ -17,6 +17,17 @@ return [
         'v1/site/doc',
         'v1/site/config',
         'v1/shop/verify-approach-order',
+        'v1/shop/no-login-reconsume',
+        'v1/shop/no-login-reconsume-sure-order',
+        'v1/shop/no-login-show-cart',
+        'v1/shop/no-login-order-detail',
+        'v1/shop/no-login-order-export',
+        'v1/config/no-login-region-list',
+        'v1/user/guest-dec',
+        'v1/user/guest-dec-debug-paid',
+        'v1/user/guest-dec-status',
+        'v1/user/guest-full-info',
+        'v1/user/guest-inspect-network',
         'v1/finance/prove-add',
         'v1/site/get-instance',
         'v1/site/languages',

+ 20 - 7
frontendApi/config/urlManagerRules.php

@@ -72,8 +72,12 @@ return [
         'extraPatterns' => [
             'GET index' => 'index',
             'GET reconsume' => 'reconsume',
+            'GET no-login-reconsume' => 'no-login-reconsume',
+            'POST no-login-reconsume-sure-order' => 'no-login-reconsume-sure-order',
             'GET goods-detail/<id>' => 'goods-detail',
             'GET show-cart' => 'show-cart',
+            'GET no-login-show-cart' => 'no-login-show-cart',
+            'GET no-login-order-detail' => 'no-login-order-detail',
             'GET reconsume-cart' => 'reconsume-cart',
             'POST sure-order' => 'sure-order',
             'POST reconsume-sure-order' => 'reconsume-sure-order',
@@ -83,6 +87,7 @@ return [
             'GET dec-order-list' => 'dec-order-list',
             'GET goods-active' => 'goods-active',
             'GET order-export/<orderSn>' => 'order-export',
+            'GET no-login-order-export/<orderSn>' => 'no-login-order-export',
             'GET dec-order-export/<orderSn>' => 'dec-order-export',
             'POST sure-approach-order' => 'sure-approach-order',
             'POST delete-approach-order' => 'delete-approach-order',
@@ -107,22 +112,29 @@ return [
         'controller' => 'v1/user',
         'extraPatterns' => [
             'GET index' => 'index',
+            'GET dec-centers' => 'dec-centers',
             'POST edit' => 'edit',
             'POST password' => 'password',
             'POST pay-password' => 'pay-password',
             'GET,POST,PUT id-card' => 'id-card',
             'GET rec-user' => 'rec-user',
+            'GET network-stats' => 'network-stats',
             'GET bind' => 'bind',
             'GET,POST bind-edit/<id>' => 'bind-edit',
-            'GET,POST dec' => 'dec',
+            'GET,POST dec' => 'dec',
+            'GET,POST guest-dec' => 'guest-dec',
+            'POST guest-dec-debug-paid' => 'guest-dec-debug-paid',
+            'GET guest-dec-status' => 'guest-dec-status',
             'GET,POST upgrade' => 'upgrade',
             'POST upgrade-info' => 'upgrade-info',
-            'GET dec-package' => 'dec-package',
-            'GET full-info' => 'full-info',
-            'GET get-auto-place' => 'get-auto-place',
-            'GET user-base-info' => 'user-base-info',
-            'GET inspect-network' => 'inspect-network',
-            'GET ba-info' => 'ba-info',
+            'GET dec-package' => 'dec-package',
+            'GET full-info' => 'full-info',
+            'GET guest-full-info' => 'guest-full-info',
+            'GET get-auto-place' => 'get-auto-place',
+            'GET user-base-info' => 'user-base-info',
+            'GET inspect-network' => 'inspect-network',
+            'GET guest-inspect-network' => 'guest-inspect-network',
+            'GET ba-info' => 'ba-info',
             'POST ba-edit' => 'ba-edit',
             'POST ba-password' => 'ba-password',
             'POST ba-pay-password' => 'ba-pay-password',
@@ -214,6 +226,7 @@ return [
             'POST ba-receive-address-default' => 'ba-receive-address-default',
             'POST ba-receive-address-delete' => 'ba-receive-address-delete',
             'GET region-list' => 'region-list',
+            'GET no-login-region-list' => 'no-login-region-list',
         ],
     ],
     [

+ 39 - 34
frontendApi/modules/v1/controllers/AtlasController.php

@@ -175,42 +175,47 @@ class AtlasController extends BaseController {
      * @throws \yii\web\HttpException
      */
     public function actionRelationList() {
-        $userName = Yii::$app->request->get('userName');
-        $deep = Yii::$app->request->get('deep', 5);
-        $periodNum = Yii::$app->request->get('periodNum', null);
-        if (!$userName) {
-            $userId = \Yii::$app->user->id;
-        } else {
-            if (!$userId = Info::getUserIdByUserName($userName)) {
-                return static::notice(Yii::t('app', 'memberDoesNotExist'), 400);
+//        try {
+            $userName = Yii::$app->request->get('userName');
+            $deep = Yii::$app->request->get('deep', 5);
+            $periodNum = Yii::$app->request->get('periodNum', null);
+            if (!$userName) {
+                $userId = \Yii::$app->user->id;
+            } else {
+                if (!$userId = Info::getUserIdByUserName($userName)) {
+                    return static::notice(Yii::t('app', 'memberDoesNotExist'), 400);
+                }
+                $topUid = \Yii::$app->user->id;
+                $userNetInfo = UserRelation::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'PARENT_UIDS');
+                $parentUidsArr = explode(',', $userNetInfo['PARENT_UIDS']);
+                if(!in_array($topUid,$parentUidsArr)){
+                    return static::notice(Yii::t('app', 'memberDoesNotInSamePlacementNetwork'), 400);
+                }
             }
-            $topUid = \Yii::$app->user->id;
-            $userNetInfo = UserRelation::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'PARENT_UIDS');
-            $parentUidsArr = explode(',', $userNetInfo['PARENT_UIDS']);
-            if(!in_array($topUid,$parentUidsArr)){
-                return static::notice(Yii::t('app', 'memberDoesNotInSamePlacementNetwork'), 400);
+            $period = Period::instance();
+            $mainUserInfo = Info::baseInfo($userId, $periodNum);
+            $decLevelConfig = Cache::getDecLevelConfig();
+            $empLevelConfig = Cache::getEmpLevelConfig();
+            $data = UserNetwork::getChildrenInDeepFromPeriodWithPage($userId, $deep, $periodNum, 1 ? ['pageSize' => 10] : []);
+            foreach($data['list'] as $key=>$value){
+                $userBaseInfo = Info::baseInfo($value['USER_ID'], $periodNum);
+                $data['list'][$key]['LIST_PERIOD_NUM'] = $periodNum?$periodNum:$period->getNowPeriodNum();
+                $data['list'][$key]['COUNT_DEEP'] = (int)($userBaseInfo['NETWORK_DEEP']);
+                $data['list'][$key]['USER_NAME'] = $userBaseInfo['USER_NAME'];
+                $data['list'][$key]['SEE_USER_NAME'] = $userBaseInfo['USER_NAME'];
+                $data['list'][$key]['REAL_NAME'] = $userBaseInfo['REAL_NAME'];
+                $data['list'][$key]['PERIOD_AT'] = $userBaseInfo['PERIOD_AT'];
+                $data['list'][$key]['DEC_LV_NAME'] = $decLevelConfig[$userBaseInfo['DEC_LV']]['LEVEL_NAME'];
+                $data['list'][$key]['EMP_LV_NAME'] = $empLevelConfig[$userBaseInfo['EMP_LV']]['LEVEL_NAME'];
             }
-        }
-        $period = Period::instance();
-        $mainUserInfo = Info::baseInfo($userId, $periodNum);
-        $decLevelConfig = Cache::getDecLevelConfig();
-        $empLevelConfig = Cache::getEmpLevelConfig();
-        $data = UserNetwork::getChildrenInDeepFromPeriodWithPage($userId, $deep, $periodNum, 1 ? ['pageSize' => 10] : []);
-        foreach($data['list'] as $key=>$value){
-            $userBaseInfo = Info::baseInfo($value['USER_ID'], $periodNum);
-            $data['list'][$key]['LIST_PERIOD_NUM'] = $periodNum?$periodNum:$period->getNowPeriodNum();
-            $data['list'][$key]['COUNT_DEEP'] = (int)($userBaseInfo['NETWORK_DEEP']);
-            $data['list'][$key]['USER_NAME'] = $userBaseInfo['USER_NAME'];
-            $data['list'][$key]['SEE_USER_NAME'] = $userBaseInfo['USER_NAME'];
-            $data['list'][$key]['REAL_NAME'] = $userBaseInfo['REAL_NAME'];
-            $data['list'][$key]['PERIOD_AT'] = $userBaseInfo['PERIOD_AT'];
-            $data['list'][$key]['DEC_LV_NAME'] = $decLevelConfig[$userBaseInfo['DEC_LV']]['LEVEL_NAME'];
-            $data['list'][$key]['EMP_LV_NAME'] = $empLevelConfig[$userBaseInfo['EMP_LV']]['LEVEL_NAME'];
-        }
-        $data['periodNum'] = $periodNum;
-        $data['listTopDeep'] = $mainUserInfo['NETWORK_DEEP'];
-
-        return static::notice($data);
+            $data['periodNum'] = $periodNum;
+            $data['listTopDeep'] = $mainUserInfo['NETWORK_DEEP'];
+
+            return static::notice($data);
+//        }catch (\Exception $e){
+//            var_dump($e->getMessage());
+//            var_dump($e->getTrace());
+//        }
     }
 
     /**

+ 17 - 1
frontendApi/modules/v1/controllers/ConfigController.php

@@ -127,6 +127,22 @@ class ConfigController extends BaseController
         return static::notice($data);
     }
 
+    /**
+     * 无需登录的行政区划列表
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionNoLoginRegionList() {
+        $countryId = \Yii::$app->request->get('countryId');
+        if (!$countryId) {
+            return static::notice('countryId is required', 400);
+        }
+
+        $data = Region::getByCountryId($countryId);
+
+        return static::notice($data);
+    }
+
     /**
      * 获取一条收货地址
      * @return mixed
@@ -291,4 +307,4 @@ class ConfigController extends BaseController
         }
         return static::notice(Yii::t('app', 'illegalRequest'), 400);
     }
-}
+}

+ 540 - 26
frontendApi/modules/v1/controllers/ShopController.php

@@ -12,6 +12,7 @@ use common\helpers\Cache;
 use common\helpers\Date;
 use common\helpers\Form;
 use common\helpers\LoggerTool;
+use common\helpers\PayStack;
 use common\helpers\Tool;
 use common\helpers\user\Info;
 use common\models\ApproachDecOrder;
@@ -46,6 +47,7 @@ use common\models\ShopGoodsNature;
 use common\models\User;
 use common\models\UserBonus;
 use common\models\UserPerformance;
+use common\services\GuestDeclarationOrderService;
 use common\models\UserWallet;
 use Yii;
 use yii\base\Exception;
@@ -203,6 +205,57 @@ class ShopController extends BaseController {
             ]);
     }
 
+    /**
+     * 无需登录的购物车订单展示
+     * @throws HttpException
+     */
+    public function actionNoLoginShowCart(){
+        $countryId = Yii::$app->request->get('countryId');
+        if (!filter_var($countryId, FILTER_VALIDATE_INT) || $countryId <= 0) {
+            return static::notice('countryId is required', 400);
+        }
+
+        $user = User::find()
+            ->select('ID,COUNTRY_ID')
+            ->where(['COUNTRY_ID' => $countryId, 'IS_DEC' => 1])
+            ->orderBy(['USER_NAME' => SORT_ASC])
+            ->asArray()
+            ->one();
+        if (!$user) {
+            return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+        }
+
+        $allAddress = ReceiveAddress::findAllAsArray('USER_ID=:USER_ID AND COUNTRY_ID=:COUNTRY_ID', [
+            ':USER_ID' => $user['ID'],
+            ':COUNTRY_ID' => $user['COUNTRY_ID'],
+        ]);
+        if ($allAddress) {
+            foreach ($allAddress as $key => $row) {
+                $allAddress[$key]['PROVINCE_NAME'] = Region::getCnName($row['PROVINCE']);
+                $allAddress[$key]['CITY_NAME'] = Region::getCnName($row['CITY']);
+                $allAddress[$key]['COUNTY_NAME'] = Region::getCnName($row['COUNTY']);
+            }
+        }
+
+        $country = Countries::getById($user['COUNTRY_ID']);
+        $coin = Currency::getById($country['LOCAL_CURRENCY_ID']);
+        $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
+
+        $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
+        $sysConfig = Cache::getSystemConfig();
+
+        return static::notice([
+            'payList' => ShopGoods::payTypesNoLogin(),
+            'allAddress' => $allAddress,
+            'sellType' => ShopGoods::getCategoryTypeNoLogin(),
+            'freight' => 0,
+            'freeShipping' => 0,
+            'isDec' => 1,
+            'coin' => 'NGN',
+            'ampDivideLine' => (float)($sysConfig['ampBVCondition']['VALUE'] ?? 0),
+        ]);
+    }
+
     /**
      * 确认订单
      */
@@ -324,55 +377,75 @@ class ShopController extends BaseController {
      * @throws \Exception
      */
     public function actionVerifyApproachOrder() {
+        LoggerTool::error('actionVerifyApproachOrder in: ');
         if (\Yii::$app->request->isPost) {
-            $request = \Yii::$app->request->post();
-
-            LoggerTool::notice($request);
+            $rawBody = \Yii::$app->request->getRawBody();
+            LoggerTool::error('actionVerifyApproachOrder in: '.$rawBody);
+            $signature = (string) \Yii::$app->request->headers->get('x-paystack-signature', '');
+            if (!PayStack::verifyWebhookSignature($rawBody, $signature, PayStack::getSecretKey())) {
+                return http_response_code(401);
+            }
+            $request = json_decode($rawBody, true);
+            if (!is_array($request) || empty($request['data']) || empty($request['data']['reference'])) {
+                return http_response_code(400);
+            }
 
             // 支付webhook回调日志
             Tool::approachOrderCall($request);
 
             try {
-                $data = $request['data'];
-                $status = $request['data']['status'] ?? 'false';
+                $webhookData = $request['data'];
+                $verified = PayStack::transactionVerify((string) $webhookData['reference']);
+                if (empty($verified['status']) || empty($verified['data']) || !is_array($verified['data'])) {
+                    LoggerTool::error('PayStack transaction verification failed for reference ' . $webhookData['reference']);
+                    return http_response_code(500);
+                }
+                $data = $verified['data'];
+                $status = $data['status'] ?? 'false';
                 // 订单状态
                 $orderStatus = ($status == 'success') ? \Yii::$app->params['orderStatus']['paid']['value'] : \Yii::$app->params['orderStatus']['failPaid']['value'];
 
                 $customFields = $data['metadata']['custom_fields'] ?? [];
-                $oderSn = $customFields[0]['value'] ?? '';
+                $orderSn = $customFields[0]['value'] ?? '';
                 $orderType = $customFields[1]['value'] ?? false;
+                if ($orderType === 'guestUserDec') {
+                    if ($status !== 'success') {
+                        (new GuestDeclarationOrderService())->markPaymentFailed((string) $data['reference'], $data);
+                        return http_response_code(200);
+                    }
+                    (new GuestDeclarationOrderService())->completePaidDraft($orderSn, $data);
+                    return http_response_code(200);
+                }
+
                 $formModel = new ApproachOrderForm();
                 $formModel->scenario = 'verifyPayStack';
                 $load = [
-                    'sn' => $oderSn,
+                    'sn' => $orderSn,
                     'scenario' => 'verifyPayStack',
                     'status' => $orderStatus,
                     'note' => [
-                        'id' => $data['id'],
-                        'domain' => $data['domain'],
-                        'status' => $data['status'],
+                        'id' => $data['id'] ?? null,
+                        'domain' => $data['domain'] ?? null,
+                        'status' => $status,
                         'reference' => $data['reference'],
-                        'amount' => $data['amount'],
-                        'created_at' => $data['created_at'],
-                        'paid_at' => $data['paid_at'],
-                        'channel' => $data['channel'],
-                        'currency' => $data['currency'],
-                        'ip_address' => $data['ip_address'],
-                        'metadata' => $data['metadata'],
-                        'customer' => $data['customer'],
+                        'amount' => $data['amount'] ?? null,
+                        'created_at' => $data['created_at'] ?? null,
+                        'paid_at' => $data['paid_at'] ?? null,
+                        'channel' => $data['channel'] ?? null,
+                        'currency' => $data['currency'] ?? null,
+                        'metadata' => $data['metadata'] ?? [],
                         'email' => $data['customer']['email'] ?? '',
                     ],
                 ];
 
                 if ($formModel->load($load, '') && $order = $formModel->verifyPayStack()) {
-                    LoggerTool::error($order);
                     return http_response_code(200);
                 } else {
                     LoggerTool::error(Form::formatErrorsForApi($formModel->getErrors()));
                     return http_response_code(500);
                 }
-            } catch (\Exception $e) {
-                LoggerTool::error(sprintf('actionVerifyApproachOrderError: File[%s], Line:[%s], Message[%s]', $e->getFile(), $e->getLine(), $e->getMessage()));
+            } catch (\Throwable $e) {
+                LoggerTool::error('actionVerifyApproachOrder failed: ' . get_class($e));
                 return http_response_code(500);
             }
         }
@@ -536,6 +609,59 @@ class ShopController extends BaseController {
         return $data;
     }
 
+    /**
+     * 无需登录查看最小编号报单中心账号的订单详情
+     */
+    public function actionNoLoginOrderDetail()
+    {
+        $orderSn = Yii::$app->request->get('orderSn');
+        if (!is_scalar($orderSn) || trim((string)$orderSn) === '') {
+            return static::notice('orderSn is required', 400);
+        }
+        $orderSn = trim((string)$orderSn);
+
+        $order = Order::find()
+            ->alias('O')
+            ->select('O.ID,O.SN,O.USER_ID,O.USER_NAME,O.ORDER_TYPE,O.ORDER_AMOUNT,O.PV,O.PAY_AMOUNT,O.PAY_PV,O.STATUS,O.CREATED_AT,O.PAY_TYPE,O.PAY_AT,O.CONSIGNEE,O.MOBILE,O.TEL,O.ADDRESS,O.CITY_NAME,O.LGA_NAME,O.PROVINCE,O.COUNTRY_ID,O.CURRENCY_ID,O.FREIGHT,O.PAY_FREIGHT,O.DELIVERY_STATUS,O.DELIVERY_PERIOD,O.DELIVERY_AT,O.EXPRESS_COMPANY,O.ORDER_TRACK_NO,O.EXPRESS_TYPE,O.FRONT_REMARK,O.PERIOD_NUM,O.WAREHOUSE,O.EMAIL,O.AUTO_MAINTENANCE,O.INVOICE_REMARK,U.REAL_NAME,C.CODE AS CURRENCY')
+            ->leftJoin(User::tableName() . ' U', 'U.ID=O.USER_ID')
+            ->leftJoin(Currency::tableName() . ' C', 'C.ID=O.CURRENCY_ID')
+            ->where(['O.SN' => $orderSn, 'O.IS_DELETE' => 0])
+            ->asArray()
+            ->one();
+
+        if (!$order) {
+            return static::notice(Yii::t('ctx', 'orderNotExist'), 400);
+        }
+
+//        $stockist = User::find()
+//            ->select('ID')
+//            ->where(['COUNTRY_ID' => $order['COUNTRY_ID'], 'IS_DEC' => 1])
+//            ->orderBy(['USER_NAME' => SORT_ASC])
+//            ->asArray()
+//            ->one();
+//        if (!$stockist || $order['USER_ID'] != $stockist['ID']) {
+//            return static::notice(Yii::t('ctx', 'orderNotExist'), 400);
+//        }
+
+        $goods = OrderGoods::find()
+            ->alias('OG')
+            ->select(['OG.SKU_CODE', 'OG.GOODS_TITLE', 'OG.BUY_NUMS', 'OG.TAX_RATE', 'OG.REAL_PV', 'OG.REAL_PRICE', 'SG.COVER'])
+            ->leftJoin(ShopGoods::tableName() . ' SG', 'SG.ID = OG.GOODS_ID')
+            ->where(['OG.ORDER_SN' => $orderSn])
+            ->asArray()
+            ->all();
+
+        $payType = $order['PAY_TYPE'];
+        $order['ORDER_TYPE'] = $order['ORDER_TYPE'] == 'ZC' ? 'Welcome Pack' : (in_array($payType, ['cash', 'pay_stack']) ? 'Repeat Purchase' : 'Points');
+        $order['PAY_TYPE'] = array_column(ShopGoods::SALE_TYPE, null, 'label')[$order['PAY_TYPE']]['name'] ?? '';
+        $order['STATUS'] = Yii::$app->params['orderStatus'][$order['STATUS']]['label'] ?? '';
+        $order['FULL_ADDRESS'] = trim(implode(', ', [$order['ADDRESS'], $order['CITY_NAME'], $order['LGA_NAME'], Region::getCnName($order['PROVINCE'])]), ', ');
+        $order['SHOW_BV'] = !in_array($payType, [5, 6]);
+        $order['COUNTRY'] = Countries::getById($order['COUNTRY_ID'])['NAME'] ?? '';
+
+        return static::notice(['order' => $order, 'goods' => $goods]);
+    }
+
     /**
      * 我的订单.(自己复消+自己加入时的首单)
      * 创建人是自己+USER_ID是自己的复消单、创建人不是自己+USER_ID是自己的报单
@@ -581,10 +707,22 @@ class ShopController extends BaseController {
         foreach ($data['list'] as $key => $value) {
             if (($value['PAY_TYPE'] == 'pay_stack') && in_array($value['STATUS'], [\Yii::$app->params['orderStatus']['notPaid']['value'], \Yii::$app->params['orderStatus']['failPaid']['value']])) {
                 // 订单中间表
-                $orderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN=:SN', [':SN' => $value['SN']], 'SKU_CODE,GOODS_TITLE,BUY_NUMS,TAX_RATE,REAL_PV,REAL_PRICE');
+                $orderGoods = ApproachOrderGoods::find()
+                    ->alias('OG')
+                    ->select(['OG.SKU_CODE', 'OG.GOODS_TITLE', 'OG.BUY_NUMS', 'OG.TAX_RATE', 'OG.REAL_PV', 'OG.REAL_PRICE', 'SG.COVER'])
+                    ->leftJoin(ShopGoods::tableName() . ' SG', 'SG.ID = OG.GOODS_ID')
+                    ->where(['OG.ORDER_SN' => $value['SN']])
+                    ->asArray()
+                    ->all();
             } else {
                 // 订单表
-                $orderGoods = OrderGoods::findAllAsArray('ORDER_SN=:SN', [':SN' => $value['SN']], 'SKU_CODE,GOODS_TITLE,BUY_NUMS,TAX_RATE,REAL_PV,REAL_PRICE');
+                $orderGoods = OrderGoods::find()
+                    ->alias('OG')
+                    ->select(['OG.SKU_CODE', 'OG.GOODS_TITLE', 'OG.BUY_NUMS', 'OG.TAX_RATE', 'OG.REAL_PV', 'OG.REAL_PRICE', 'SG.COVER'])
+                    ->leftJoin(ShopGoods::tableName() . ' SG', 'SG.ID = OG.GOODS_ID')
+                    ->where(['OG.ORDER_SN' => $value['SN']])
+                    ->asArray()
+                    ->all();
             }
             $data['list'][$key]['hasChildren'] = $orderGoods;
             $data['list'][$key]['ORDER_TYPE'] = $value['ORDER_TYPE']=='ZC' ? 'Welcome Pack' : (in_array($value['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Repeat Purchase': 'Points');
@@ -647,10 +785,22 @@ class ShopController extends BaseController {
         foreach ($data['list'] as $key => $value) {
             if (($value['PAY_TYPE'] == 'pay_stack') && in_array($value['STATUS'], [\Yii::$app->params['orderStatus']['notPaid']['value'], \Yii::$app->params['orderStatus']['failPaid']['value']])) {
                 // 订单中间表
-                $orderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN=:SN', [':SN' => $value['SN']], 'SKU_CODE,GOODS_TITLE,BUY_NUMS,TAX_RATE,REAL_PV,REAL_PRICE');
+                $orderGoods = ApproachOrderGoods::find()
+                    ->alias('OG')
+                    ->select(['OG.SKU_CODE', 'OG.GOODS_TITLE', 'OG.BUY_NUMS', 'OG.TAX_RATE', 'OG.REAL_PV', 'OG.REAL_PRICE', 'SG.COVER'])
+                    ->leftJoin(ShopGoods::tableName() . ' SG', 'SG.ID = OG.GOODS_ID')
+                    ->where(['OG.ORDER_SN' => $value['SN']])
+                    ->asArray()
+                    ->all();
             } else {
                 // 订单表
-                $orderGoods = OrderGoods::findAllAsArray('ORDER_SN=:SN', [':SN' => $value['SN']], 'SKU_CODE,GOODS_TITLE,BUY_NUMS,TAX_RATE,REAL_PV,REAL_PRICE');
+                $orderGoods = OrderGoods::find()
+                    ->alias('OG')
+                    ->select(['OG.SKU_CODE', 'OG.GOODS_TITLE', 'OG.BUY_NUMS', 'OG.TAX_RATE', 'OG.REAL_PV', 'OG.REAL_PRICE', 'SG.COVER'])
+                    ->leftJoin(ShopGoods::tableName() . ' SG', 'SG.ID = OG.GOODS_ID')
+                    ->where(['OG.ORDER_SN' => $value['SN']])
+                    ->asArray()
+                    ->all();
             }
             $data['list'][$key]['hasChildren'] = $orderGoods;
             $data['list'][$key]['ORDER_TYPE'] = $value['ORDER_TYPE']=='ZC' ? 'Welcome Pack' : (in_array($value['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Repeat Purchase': 'Points');
@@ -699,6 +849,66 @@ class ShopController extends BaseController {
         return static::notice($data);
     }
 
+    /**
+     * 根据国家获取最小编号的报单中心账号(无需登录)
+     */
+    public function actionNoLoginReconsume() {
+        $countryId = Yii::$app->request->get('countryId');
+        if (!filter_var($countryId, FILTER_VALIDATE_INT) || $countryId <= 0) {
+            return static::notice('countryId is required', 400);
+        }
+
+        $user_one = User::find()
+            ->select('ID,USER_NAME')
+            ->where(['COUNTRY_ID' => $countryId, 'IS_DEC' => 1])
+            ->orderBy(['USER_NAME' => SORT_ASC])
+            ->asArray()
+            ->one();
+
+        if (!$user_one) {
+            return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+        }
+//        var_dump($user_one['ID']);die();
+
+        // 会员信息
+        $user = User::findOneAsArray('ID=:ID', [':ID' => $user_one['ID']]);
+        if (!$user) {
+            return static::notice(Yii::t('app', 'memberDoesNotExist'), 400);
+        }
+
+//        $condition = ' AND S.STATUS=1 AND S.CATEGORY_TYPE=1 AND FIND_IN_SET(1,S.GIFT_TYPE)>0 AND (S.INSTALMENT=0 OR S.INSTALMENT=1) AND N.COUNTRY_ID=:COUNTRY_ID';
+//        $data = ShopGoods::lists($condition, [':COUNTRY_ID' => $user['COUNTRY_ID']], [
+//            'select' => 'S.*,N.MARKET_PRICE,N.SELL_PRICE,N.TAX_RATE,N.LOCAL_CURRENCY_ID,N.COUNTRY_ID',
+//            'from' => ShopGoods::tableName() . ' AS S',
+//            'join' => [
+//                ['INNER JOIN', ShopGoodsNature::tableName() . ' AS N', 'N.GOODS_ID = S.ID'],
+//            ],
+//            'orderBy' => 'SORT ASC,CREATED_AT DESC',
+//            'limit' => 100,
+//        ]);
+
+        $condition = ' AND STATUS=1 AND (FIND_IN_SET(2,GIFT_TYPE)>0 OR FIND_IN_SET(4,GIFT_TYPE)>0) AND S.INSTALMENT=0 AND N.COUNTRY_ID=:COUNTRY_ID';
+        $data = ShopGoods::lists($condition, [':COUNTRY_ID' => $user['COUNTRY_ID']], [
+            'select' => 'S.*,N.MARKET_PRICE,N.SELL_PRICE,N.TAX_RATE,N.LOCAL_CURRENCY_ID,N.COUNTRY_ID',
+            'from' => ShopGoods::tableName() . ' AS S',
+            'join' => [
+                ['INNER JOIN', ShopGoodsNature::tableName() . ' AS N', 'N.GOODS_ID = S.ID'],
+            ],
+            'orderBy' => 'SORT ASC,CREATED_AT DESC',
+            'limit' => 100,
+        ]);
+
+        $currencies = Currency::getAllData();
+        $currencies = array_column($currencies, NULL, 'ID');
+
+        foreach ($data['list'] as $key => $value) {
+            $data['list'][$key]['DISCOUNT'] = in_array($value['TYPE'], [1, 2]) ? ShopGoods::getGoodType()[$value['TYPE']]['discount'] : $value['SELL_DISCOUNT'] * 100;
+            $data['list'][$key]['COIN'] = $currencies[$value['LOCAL_CURRENCY_ID']]['CODE'] ?? '';
+        }
+
+        return static::notice($data);
+    }
+
     /**
      * 帮会员复消购物车
      * @throws HttpException
@@ -766,6 +976,43 @@ class ShopController extends BaseController {
         }
     }
 
+    /**
+     * 无需登录的复消确认订单
+     */
+    public function actionNoLoginReconsumeSureOrder(){
+        $post = Yii::$app->request->post();
+        $countryId = $post['countryId'] ?? null;
+        if (!filter_var($countryId, FILTER_VALIDATE_INT) || $countryId <= 0) {
+            return static::notice('countryId is required', 400);
+        }
+
+        $user = User::find()
+            ->select('ID,USER_NAME')
+            ->where(['COUNTRY_ID' => $countryId, 'IS_DEC' => 1])
+            ->orderBy(['USER_NAME' => SORT_ASC])
+            ->asArray()
+            ->one();
+        if (!$user) {
+            return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+        }
+
+        $formModel = new ApproachReconsumeOrderForm();
+        $formModel->scenario = 'noLoginReconsumeOrder';
+        $formModel->remark = Yii::t('app', 'reconsume');
+        $formModel->noLoginUserId = $user['ID'];
+        $post['type'] = DeclarationForm::TYPE_FX;
+        $post['payType'] = 'pay_stack';
+        if ($formModel->load($post, '')) {
+            $formModel->userName = $user['USER_NAME'];
+            $formModel->decUserName = $user['USER_NAME'];
+            if ($order = $formModel->add()) {
+                return static::notice($order);
+            }
+        }
+
+        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
+    }
+
     /**
      * 商品列表tabs分类
      * @return mixed
@@ -806,7 +1053,6 @@ class ShopController extends BaseController {
      */
     public function actionOrderExport()
     {
-        $uname = Info::getUserNameByUserId(\Yii::$app->user->id);
         $orderSn = \Yii::$app->request->get('orderSn');
 
         $condition = " AND SN=:SN AND O.IS_DELETE = 0";
@@ -1065,6 +1311,272 @@ ORDER;
         return static::notice(['fileUrl' => $path, 'targetName' => $file_name]);
     }
 
+    /**
+     * 无需登录导出订单.
+     * @return mixed
+     * @throws HttpException
+     * @throws \Mpdf\MpdfException
+     */
+    public function actionNoLoginOrderExport()
+    {
+        $orderSn = \Yii::$app->request->get('orderSn');
+
+        $condition = " AND SN=:SN AND O.IS_DELETE = 0";
+        $params = [
+            ':SN' => $orderSn,
+        ];
+
+        $data = Order::lists($condition, $params, [
+            'select' => 'O.*,U.REAL_NAME,OG.*,OG.CATEGORY_TYPE',
+            'orderBy' => 'O.CREATED_AT DESC',
+            'from' => Order::tableName() . ' AS O',
+            'join' => [
+                ['LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID'],
+                ['LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN'],
+            ],
+        ]);
+        if (!$data['list']) {
+            $condition .= ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)';
+            $params[':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value'];   // 待支付
+            $params[':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value'];   // 支付失败
+            $data = ApproachOrder::lists($condition, $params, [
+                'select' => 'O.*,U.REAL_NAME,OG.*,OG.CATEGORY_TYPE',
+                'orderBy' => 'O.CREATED_AT DESC',
+                'from' => ApproachOrder::tableName() . ' AS O',
+                'join' => [
+                    ['LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID'],
+                    ['LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN'],
+                ],
+            ]);
+        }
+
+        $userId = '';
+        $userName = '';
+        $address = '';
+        $mobile = '';
+        $orderAt = '';
+        $orderDetails = '';
+        $orderAmount = 0;  // 合计总额
+        $orderNums = 0; // 合计总数
+        $totalTaxAmount = 0; // 合计税额
+        $totalAmount = 0;
+        foreach ($data['list'] as $key => $value) {
+            $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
+            $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
+            $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
+
+            $userId = $value['USER_NAME'];
+            $userName = $value['CONSIGNEE'];
+            $address = $provinceName .' '. $cityName .' '. $countyName .' '. $value['ADDRESS'];
+            $mobile = $value['MOBILE'];
+            $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
+
+            // 总价
+            $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
+            $orderAmount += $totalAmount;
+            $orderNums += $value['BUY_NUMS'];
+            // 税额
+            $taxAmount = floatval(Tool::formatPrice(($value['REAL_PRICE'] - ($value['REAL_PRICE'] / (1 + $value['TAX_RATE'] / 100))) * $value['BUY_NUMS']));
+            $totalTaxAmount += $taxAmount;
+            $productAmount = Tool::formatAmount($value['REAL_PRICE']);
+            $taxAmount = Tool::formatAmount($taxAmount);
+            $totalAmount = Tool::formatAmount($totalAmount);
+            // 订单详情
+            $orderDetails .= <<<EOT
+                <tr>
+                    <td style="text-align: center;">{$value['SKU_CODE']}</td>
+                    <td style="text-align: center;">{$value['GOODS_TITLE']}</td>
+                    <td style="text-align: right;">{$productAmount}</td>
+                    <td style="text-align: right;">{$value['BUY_NUMS']}</td>
+                    <td style="text-align: right;">{$value['TAX_RATE']}%</td>
+                    <td style="text-align: right;">{$taxAmount}</td>
+                    <td style="text-align: right;">{$totalAmount}</td> 
+                </tr>
+EOT;
+        }
+
+        $memberCode = Yii::t('app', 'memberCode');
+        $memberName = Yii::t('app', 'memberName');
+        $memberAddress = Yii::t('app', 'memberAddress');
+        $memberPhone = Yii::t('app', 'memberPhone');
+        $orderCode = Yii::t('app', 'orderCode');
+        $orderDetail = Yii::t('app', 'orderDetail');
+        $productCode = Yii::t('app', 'productCode');
+        $productName = Yii::t('app', 'productName');
+        $productPrice = Yii::t('app', 'productPrice');
+        $quantity = Yii::t('app', 'qty');
+        $taxRate = Yii::t('app', 'taxRate');
+        $totalTax = Yii::t('app', 'totalTax');
+        $totalAmount = Yii::t('app', 'totalAmount');
+        $total = Yii::t('app', 'total');
+        $signature = Yii::t('app', 'signature');
+        $date = Yii::t('app', 'date');
+        $createAt = Yii::t('app', 'createAt');
+
+        // 订单基本信息
+        $orderBase = <<<ORDER
+            <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberCode}</td>
+                    <td width="70%"></td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberName}</td>
+                    <td width="70%">{$userName}</td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberAddress}</td>
+                    <td width="70%">{$address}</td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberPhone}</td>
+                    <td width="70%">{$mobile}</td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$orderCode}</td>
+                    <td width="70%">{$orderSn}</td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$createAt}</td>
+                    <td width="70%">{$orderAt}</td>
+                </tr>
+                <tr>
+                    <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">{$orderDetail}</td>
+                    <td class="bg"></td>
+                </tr>
+            </table>
+ORDER;
+
+        $l['a_meta_charset'] = 'UTF-8';
+        $l['a_meta_dir'] = 'ltr';
+        $l['a_meta_language'] = 'zh';
+        $l['w_page'] = '页面';
+
+        $orderAmount = Tool::formatAmount($orderAmount);
+        $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
+
+        $context = <<<ORDER
+            <!doctype html>
+            <html lang="en">
+            <head>
+                <meta charset="UTF-8" />
+                <title>{$orderDetail}</title>
+                <style>
+                    table {
+                        border-collapse: collapse;
+                    }
+                    table td, table th {
+                        border: 1px solid #ccc;
+                        /*padding: 5px 5px;*/
+                        border-collapse: collapse;
+                    }
+                    /*td {*/
+                    /*    padding: 120px;*/
+                    /*}*/
+                    .bg {
+                        background-color: #ccc;
+                    }
+                </style>
+            </head>
+            <body>
+                <div class="content">
+                    <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>{$orderDetail}</b><br></p>
+                    <div>
+                        <div style="display: block; width: 100%;">
+                            {$orderBase}
+                            
+                            <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
+                                <tr>
+                                    <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productCode}</th>
+                                    <th width="20%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productName}</th>
+                                    <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productPrice}</th>
+                                    <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">{$quantity}</th>
+                                    <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">{$taxRate}</th>
+                                    <th width="13%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalTax}</th>
+                                    <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalAmount}</th>
+                                </tr>
+                                {$orderDetails}
+                                <tr>
+                                    <td colspan="3">{$total}</td>
+                                    <td style="text-align: right;">{$orderNums}</td>
+                                    <td></td>
+                                    <td style="text-align: right;">{$totalTaxAmount}</td>
+                                    <td style="text-align: right;">{$orderAmount}</td>
+                                </tr>
+                            </table>
+                        </div>
+                        
+                        <div style="width: 100%; margin-top: 50px; height: 30px;">
+                            <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
+                                <tr style="border: none;">
+                                    <td width="70%" style="border: none;"></td>
+                                    <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$signature}:</td>
+                                </tr>
+                                <tr style="border: none;">
+                                    <td width="70%" style="border: none;"></td>
+                                    <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$date}:</td>
+                                </tr>
+                            </table>
+                        </div>
+                    </div>
+                </div>
+            </body>
+            </html>
+ORDER;
+        require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
+
+        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
+        // 设置打印模式
+        $pdf->SetCreator(PDF_CREATOR);
+        $pdf->SetAuthor('DaZe');
+        $pdf->SetTitle($orderSn);
+        $pdf->SetSubject('TCPDF Tutorial');
+        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
+        // 是否显示页眉
+        $pdf->setPrintHeader(false);
+        // 设置页眉字体
+        $pdf->setHeaderFont(Array('dejavusans', '', '12'));
+        // 页眉距离顶部的距离
+        $pdf->SetHeaderMargin('5');
+        // 是否显示页脚
+        $pdf->setPrintFooter(false);
+        // 设置默认等宽字体
+        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
+        // 设置行高
+        $pdf->setCellHeightRatio(1);
+        // 设置左、上、右的间距
+        $pdf->SetMargins('10', '0', '10');
+        // 设置是否自动分页  距离底部多少距离时分页
+        $pdf->SetAutoPageBreak(TRUE, '15');
+        // 设置图像比例因子
+        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
+        if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
+            require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
+            $pdf->setLanguageArray($l);
+        }
+        $pdf->setFontSubsetting(true);
+        $pdf->AddPage();
+        // 设置字体
+        $pdf->SetFont('stsongstdlight', '', 10, '', true);
+        //        $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
+//        if (!file_exists($image_file)) {
+//            $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
+//        }
+        $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
+        $image = file_get_contents($image_file);
+        $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
+        $pdf->writeHTML($context);
+
+        ob_clean();
+
+        $file_name = $orderSn . '.pdf';
+        $path = 'pdfs/' . $file_name;
+        $pdf->Output(Yii::$app->basePath . '/web/' . $path, 'F');
+        @exec('chmod -R 777 /' . Yii::$app->basePath . '/web' . $path);
+
+        return static::notice(['fileUrl' => $path, 'targetName' => $file_name]);
+    }
+
     /**
      * 导出订单.
      * @return mixed
@@ -1999,3 +2511,5 @@ ORDER;
         }
     }
 }
+
+

+ 306 - 0
frontendApi/modules/v1/controllers/UserController.php

@@ -36,16 +36,20 @@ use common\models\forms\UserBindForm;
 use common\models\forms\UserForm;
 use common\models\Instalment;
 use common\models\OpenBank;
+use common\models\OrderDec;
+use common\models\OriginDecPv;
 use common\models\Period;
 use common\models\ReceiveAddress;
 use common\models\Region;
 use common\models\ShopGoods;
 use common\models\ShopGoodsNature;
+use common\services\GuestDeclarationOrderService;
 use common\models\UpgradeType;
 use common\models\User;
 use common\models\UserBind;
 use common\models\UserBonus;
 use common\models\UserInfo;
+use common\models\UserRelation;
 use common\models\BaUserInfo;
 use common\models\UserNetwork;
 use common\models\forms\DeclarationUpgradeForm;
@@ -61,6 +65,39 @@ class UserController extends BaseController {
 
     const LOOP_FINISH = 1;
 
+    public function behaviors() {
+        $behaviors = parent::behaviors();
+        $behaviors['authenticator']['optional'] = array_merge(
+            $behaviors['authenticator']['optional'] ?? [],
+            ['dec-centers']
+        );
+        return $behaviors;
+    }
+
+    /**
+     * 按国家查询有效报单中心
+     * @return array
+     */
+    public function actionDecCenters() {
+        $countryId = Yii::$app->request->get('countryId');
+        if ($countryId === null || $countryId === '') {
+            return static::notice('countryId is required', 400);
+        }
+
+        $centers = User::find()
+            ->select('ID,USER_NAME,REAL_NAME,MOBILE,DEC_ADDRESS,DEC_PHONE,DEC_PROVINCE,DEC_CITY,DEC_COUNTY,DEC_ROLE_ID')
+            ->where([
+                'COUNTRY_ID' => $countryId,
+                'IS_DEC' => 1,
+                'STATUS' => 1,
+                'DELETED' => 0,
+            ])
+            ->asArray()
+            ->all();
+
+        return static::notice($centers);
+    }
+
     /**
      * 会员资料
      * @return mixed
@@ -145,6 +182,50 @@ class UserController extends BaseController {
         return static::notice($allData);
     }
 
+    /**
+     * 当前用户的安置网络下线统计
+     * @return mixed
+     */
+    public function actionNetworkStats() {
+        $userId = Yii::$app->user->id;
+        $relationInfo = UserRelation::find()
+            ->select(['TOP_DEEP'])
+            ->where(['USER_ID' => $userId])
+            ->asArray()
+            ->one();
+
+        $descendants = [];
+        if ($relationInfo) {
+            $descendants = UserRelation::find()
+                ->alias('R')
+                ->select(['R.USER_ID', 'R.PARENT_UID', 'R.TOP_DEEP'])
+                ->innerJoin(User::tableName() . ' U', 'U.ID = R.USER_ID')
+                ->where('FIND_IN_SET(:USER_ID, R.PARENT_UIDS)', [':USER_ID' => $userId])
+                ->andWhere(['>', 'R.TOP_DEEP', $relationInfo['TOP_DEEP']])
+                ->andWhere(['U.DELETED' => 0])
+                ->asArray()
+                ->all();
+        }
+
+        $userIds = array_column($descendants, 'USER_ID');
+        $pcv = 0;
+        if ($userIds) {
+            $pcv += (float) DecOrder::find()->where(['TO_USER_ID' => $userIds, 'IS_DEL' => 0])->sum('DEC_PV');
+            $pcv += (float) OrderDec::find()->where(['USER_ID' => $userIds, 'IS_DELETE' => 0])->sum('PAY_PV');
+            $pcv += (float) OriginDecPv::find()->where(['USER_ID' => $userIds])->sum('DEC_PV');
+        }
+
+        $maxDeep = $descendants ? max(array_column($descendants, 'TOP_DEEP')) : $relationInfo['TOP_DEEP'] ?? 0;
+        return static::notice([
+            'DOWNLINE_COUNT' => count($descendants),
+            'DIRECT_DOWNLINE_COUNT' => count(array_filter($descendants, function ($downline) use ($userId) {
+                return $downline['PARENT_UID'] === $userId;
+            })),
+            'MAX_DOWNLINE_DEEP' => max(0, (int) $maxDeep - (int) ($relationInfo['TOP_DEEP'] ?? 0)),
+            'DOWNLINE_PCV' => $pcv,
+        ]);
+    }
+
     /**
      * 上传身份证
      * @return mixed
@@ -515,6 +596,133 @@ class UserController extends BaseController {
     /**
      * 报单管理
      */
+    public function actionGuestDec()
+    {
+        $service = new GuestDeclarationOrderService();
+        try {
+            if (Yii::$app->request->isPost) {
+                $input = Yii::$app->request->post();
+                $result = $service->submitDraft(
+                    (string) ($input['draftId'] ?? ''),
+                    (string) ($input['accessToken'] ?? ''),
+                    $input
+                );
+                return static::notice($result);
+            }
+
+            $countryId = (string) Yii::$app->request->get('countryId', '');
+            if ($countryId === '') {
+                return static::notice(Yii::t('app', 'countryDoesNotSelect'), 400);
+            }
+            $draft = $service->createDraft($countryId);
+            $decLevels = Cache::getDecLevelConfig();
+            $packages = DeclarationPackage::getAllData();
+            foreach ($packages as $index => $package) {
+                $packages[$index]['LEVEL_NAME'] = $decLevels[$package['LEVEL_ID']]['LEVEL_NAME'] ?? '';
+            }
+
+//            $query_condition = " AND (1<>1";
+//            if(!$isDecReg || ($isDecReg && $isDec==1)){
+//                $query_condition = " AND (FIND_IN_SET(1, S.GIFT_TYPE)>0";
+//            }
+//            if($isStudio==1){
+//                $query_condition .= " OR FIND_IN_SET(3, S.GIFT_TYPE)>0";
+//            }
+//            $query_condition .= ") AND (S.INSTALMENT=0 OR S.INSTALMENT=1) AND N.COUNTRY_ID=:COUNTRY_ID";
+
+            // 只查询普通商品
+//            $allGoods = ShopGoods::find()
+//                ->alias('S')
+//                ->select('S.*,N.MARKET_PRICE,N.SELL_PRICE,N.TAX_RATE,N.LOCAL_CURRENCY_ID,N.COUNTRY_ID,C.CODE')
+//                ->join('INNER JOIN', ShopGoodsNature::tableName() . ' AS N', 'N.GOODS_ID=S.ID')
+//                ->join('INNER JOIN', Currency::tableName() . ' AS C', 'C.ID=N.LOCAL_CURRENCY_ID')
+//                ->where("STATUS=1 AND CATEGORY_TYPE=1 " . $query_condition, [':COUNTRY_ID' => $countryId])
+//                ->orderBy('SORT ASC')
+//                ->asArray()
+//                ->all();
+            $goods = ShopGoods::find()
+                ->alias('S')
+                ->select('S.*,N.MARKET_PRICE,N.SELL_PRICE,N.TAX_RATE,N.LOCAL_CURRENCY_ID,N.COUNTRY_ID,C.CODE')
+                ->innerJoin(ShopGoodsNature::tableName() . ' N', 'N.GOODS_ID=S.ID')
+                ->innerJoin(Currency::tableName() . ' C', 'C.ID=N.LOCAL_CURRENCY_ID')
+                ->where('S.STATUS=1 AND S.CATEGORY_TYPE=1 AND FIND_IN_SET(1,S.GIFT_TYPE)>0 AND (S.INSTALMENT=0 OR S.INSTALMENT=1) AND N.COUNTRY_ID=:COUNTRY_ID', [':COUNTRY_ID' => $countryId])
+                ->orderBy('S.SORT ASC')
+                ->asArray()->all();
+
+
+            // 银行开户行
+            $allOpenBank = OpenBank::find()
+                ->where('STATUS=:STATUS AND COUNTRY_ID=:COUNTRY_ID', [':STATUS' => 1, ':COUNTRY_ID' => $countryId])
+                ->orderBy('BANK_NAME ASC')
+                ->asArray()
+                ->all();
+            // 售卖方式
+            $sellType = ShopGoods::getCategoryType();
+//            unset($sellType[0]['sell_type'][1]);
+
+            return static::notice([
+                'draft' => $draft,
+                'allDecPackage' => $packages,
+                'allGoods' => $goods,
+                'allOpenBank' => $allOpenBank,
+                'sellType' => $sellType,
+                'categoryType' => ShopGoods::getCategoryType()[0]['id'],
+                'region' => Region::getByCountryId($countryId),
+                'payList' => ['pay_stack' => ['name' => 'PayStack']],
+                'decLevel' => DeclarationLevel::getData(),
+            ]);
+        } catch (\Throwable $e) {
+            LoggerTool::error([
+                'event' => 'guestDec_failed',
+                'exception' => get_class($e),
+                'message' => $e->getMessage(),
+                'file' => basename($e->getFile()),
+                'line' => $e->getLine(),
+            ]);
+            if ($e instanceof \yii\web\HttpException) {
+                return static::notice($e->getMessage(), $e->statusCode);
+            }
+            return static::notice('Unable to process guest order.', 500);
+        }
+    }
+
+    public function actionGuestDecDebugPaid()
+    {
+        try {
+            $input = Yii::$app->request->post();
+            $result = (new GuestDeclarationOrderService())->debugCompletePaidDraft(
+                (string) ($input['draftId'] ?? ''),
+                (string) ($input['accessToken'] ?? '')
+            );
+            return static::notice($result);
+        } catch (\Throwable $e) {
+            LoggerTool::error([
+                'event' => 'guestDec_debug_paid_failed',
+                'exception' => get_class($e),
+                'message' => $e->getMessage(),
+                'file' => basename($e->getFile()),
+                'line' => $e->getLine(),
+            ]);
+            if ($e instanceof \yii\web\HttpException) {
+                return static::notice($e->getMessage(), $e->statusCode);
+            }
+            return static::notice('Unable to debug-complete guest order.', 500);
+        }
+    }
+
+    public function actionGuestDecStatus()
+    {
+        try {
+            $result = (new GuestDeclarationOrderService())->getDraftStatus(
+                (string) Yii::$app->request->get('draftId', ''),
+                (string) Yii::$app->request->get('accessToken', '')
+            );
+            return static::notice($result);
+        } catch (\Throwable $e) {
+            return static::notice('Guest order draft was not found.', 404);
+        }
+    }
+
     public function actionDec() {
         $redis = \Yii::$app->redis;
         $post = \Yii::$app->request->post();
@@ -825,6 +1033,37 @@ SQL;
         }
     }
 
+    /**
+     * Public member information lookup for guest declaration flows.
+     * @return mixed
+     */
+    public function actionGuestFullInfo()
+    {
+        $userName = trim((string) \Yii::$app->request->get('userName', ''));
+        $userId = Info::getUserIdByUserName($userName);
+        $user = $userId ? User::findOneAsArray('ID=:ID', [':ID' => $userId]) : null;
+        if (!$user) {
+            return static::notice(Yii::t('app', 'memberNumberDoesNotExist'), 400);
+        }
+
+        $allChildUser = UserNetwork::getFirstFloorChildren($userId);
+        $isLocation = [1 => 'Left-Null', 2 => 'Right-Null'];
+        if ($allChildUser) {
+            foreach ($allChildUser as $child) {
+                if ($child['RELATIVE_LOCATION'] < '3' && isset($isLocation[$child['RELATIVE_LOCATION']])) {
+                    $isLocation[$child['RELATIVE_LOCATION']] = str_replace('Null', 'Full', $isLocation[$child['RELATIVE_LOCATION']]);
+                }
+            }
+        }
+
+        return static::notice([
+            'REAL_NAME' => $user['REAL_NAME'],
+            'countryId' => $user['COUNTRY_ID'],
+            'userId' => $userId,
+            'isLocation' => '(' . implode(',', $isLocation) . ')',
+        ]);
+    }
+
     public function actionInspectNetwork()
     {
         // 推荐人信息
@@ -906,6 +1145,73 @@ SQL;
         return static::notice(Yii::t('ctx', 'fillSponsorUpline'), 400);
     }
 
+    /**
+     * Public sponsor relationship validation for guest declaration flows.
+     * @return mixed
+     */
+    public function actionGuestInspectNetwork()
+    {
+        $recommenderName = trim((string) \Yii::$app->request->get('recommenderName', ''));
+        $recommenderActualName = trim((string) \Yii::$app->request->get('recommenderActualName', ''));
+        if ($recommenderName === '' || $recommenderActualName === '') {
+            return static::notice(Yii::t('app', 'memberNumberDoesNotExist'), 400);
+        }
+
+        $userId = Info::getUserIdByUserName($recommenderName);
+        $recommender = $userId ? User::findOneAsArray('ID=:ID', [':ID' => $userId]) : null;
+        if (!$recommender) {
+            return static::notice(Yii::t('app', 'memberNumberDoesNotExist'), 400);
+        }
+
+        $actualId = Info::getUserIdByUserName($recommenderActualName);
+        $recommenderActual = $actualId ? User::findOneAsArray('ID=:ID', [':ID' => $actualId]) : null;
+        if (!$recommenderActual) {
+            return static::notice(Yii::t('app', 'memberNumberDoesNotExist'), 400);
+        }
+
+        if ($actualId == $userId) {
+            return static::notice([
+                'REAL_NAME' => $recommenderActual['REAL_NAME'],
+                'userId' => $recommenderActual['ID'],
+            ]);
+        }
+
+        $sqlUp = <<<SQL
+            WITH recursive t_rec AS
+            (
+                SELECT m.USER_ID, U.USER_NAME, m.PARENT_UID, U2.USER_NAME AS PARENT_NAME, 1 AS node_level
+                FROM AR_USER_RELATION_NEW m
+                LEFT JOIN AR_USER U ON U.ID = m.USER_ID
+                LEFT JOIN AR_USER U2 ON U2.ID = m.PARENT_UID
+                WHERE U.USER_NAME = :USER_NAME
+
+                UNION ALL
+
+                SELECT t1.USER_ID, U.USER_NAME, t1.PARENT_UID, U2.USER_NAME AS PARENT_NAME,
+                       t2.node_level + 1
+                FROM AR_USER_RELATION_NEW t1
+                JOIN t_rec t2 ON t2.PARENT_UID = t1.USER_ID
+                LEFT JOIN AR_USER U ON U.ID = t1.USER_ID
+                LEFT JOIN AR_USER U2 ON U2.ID = t1.PARENT_UID
+            )
+            SELECT * FROM t_rec
+SQL;
+
+        $relationNodeUp = \Yii::$app->db->createCommand($sqlUp)
+            ->bindValue(':USER_NAME', $recommenderName)
+            ->queryAll();
+        $relationNodeUp = array_column($relationNodeUp, 'USER_NAME');
+
+        if (in_array($recommenderActualName, $relationNodeUp, true)) {
+            return static::notice([
+                'REAL_NAME' => $recommenderActual['REAL_NAME'],
+                'userId' => $recommenderActual['ID'],
+            ]);
+        }
+
+        return static::notice(Yii::t('ctx', 'fillSponsorUpline'), 400);
+    }
+
     /**
      * 复消会员信息查询
      * @return mixed