Browse Source

feat: EK-76: Member Auto-Maintenance.

kevinElken 10 months ago
parent
commit
70183ac9df

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

@@ -74,6 +74,7 @@ class ShopController extends BaseController {
             'SELL_TYPE'=> 'SELL_TYPE',
             'PRICE_PV'=> 'PRICE_PV',
             'CATEGORY_TYPE' => 'CATEGORY_TYPE',
+            'AUTO_MAINTENANCE' => 'AUTO_MAINTENANCE',
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
@@ -111,6 +112,7 @@ class ShopController extends BaseController {
             'SELL_TYPE'=> 'SELL_TYPE',
             'PRICE_PV'=> 'PRICE_PV',
             'CATEGORY_TYPE' => 'CATEGORY_TYPE',
+            'AUTO_MAINTENANCE' => 'AUTO_MAINTENANCE',
         ]);
         $form = new ShopExportForm();
         $result = $form->run($filter, \Yii::t('ctx', 'shopExportListName')); // 商品列表

+ 9 - 0
backendApi/modules/v1/models/lists/shop/GoodsList.php

@@ -149,6 +149,15 @@ class GoodsList extends \common\libs\dataList\DataList implements DataListInterf
                     },
                     'headerOther' => ['width' => '190'],
                 ],
+                'AUTO_MAINTENANCE' => [
+                    'header' => \Yii::t('ctx', 'shopListAutoMaintenance'),
+                    'value' => function($row) {
+                        return $row['AUTO_MAINTENANCE'] == 1 ? \Yii::t('ctx', 'yes') : \Yii::t('ctx', 'no');
+                    },
+                    'headerOther' => [
+                        'width' => '110',
+                    ],
+                ],
             ];
         }
         return $this->columns;

+ 2 - 0
common/messages/en-US/app.php

@@ -33,6 +33,8 @@ return [
     'instalmentGoodsNoError' => 'Products No. error',
     'instalmentOrderInProcess' => '分期商品订单未完成',
     'productsDoesSoldOut' => 'Products has sold out!',
+    'productsDoesNotAmp' => 'Products does not Auto Maintenance!',
+    'ampOrderSubStandard' => 'Minimum {ampBv} amp BV required. Please meet that criteria to proceed with the purchase.',
     'cashDoesNotAdequate' => 'Insufficient balance, unable to make the payment.',
     'userPerformanceDoesNotAdequate' => 'Performance bonus, unable to make the payment.',
     'exchangePointDoesNotAdequate' => '兑换积分不足,无法购买商品',

+ 1 - 0
common/messages/en-US/ctx.php

@@ -212,6 +212,7 @@ return [
     'shopListTax' => 'Tax(₦)',
     'shopListInventory' => 'Inventory',
     'shopListStatus' => 'Status',
+    'shopListAutoMaintenance' => 'AMP',
     'shopListOnSale' => 'On sale',
     'shopListSoldOut' => 'Sold out',
     'shopListUpdatedAt' => 'Update Time',

+ 2 - 0
common/messages/zh-CN/app.php

@@ -33,6 +33,8 @@ return [
     'instalmentGoodsNoError' => '分期商品的期数错误',
     'instalmentOrderInProcess' => '分期商品订单未完成',
     'productsDoesSoldOut' => '商品已下架',
+    'productsDoesNotAmp' => '非AMP商品!',
+    'ampOrderSubStandard' => 'AMP订单最少需要 {ampBv} BV. 请满足该标准以继续购买.',
     'cashDoesNotAdequate' => '余额不足,无法购买商品',
     'userPerformanceDoesNotAdequate' => '绩效奖金不足,无法购买商品',
     'exchangePointDoesNotAdequate' => '兑换积分不足,无法购买商品',

+ 1 - 0
common/messages/zh-CN/ctx.php

@@ -202,6 +202,7 @@ return [
     'shopListTax' => '税额(₦)',
     'shopListInventory' => '库存',
     'shopListStatus' => '状态',
+    'shopListAutoMaintenance' => 'AMP',
     'shopListOnSale' => '已上架',
     'shopListSoldOut' => '已下架',
     'shopListUpdatedAt' => '更新时间',

+ 49 - 0
common/models/AmpPeriod.php

@@ -0,0 +1,49 @@
+<?php
+
+namespace common\models;
+
+/**
+ * This is the model class for table "{{%AMP_PERIOD}}".
+ *
+ * @property string ID
+ * @property string USER_ID 用户ID
+ * @property string ORDER_SN 订单号
+ * @property int    PERIOD_NUM 周期
+ * @property double BV BV
+ */
+class AmpPeriod extends \common\components\ActiveRecord
+{
+    /**
+     * @inheritdoc
+     */
+    public static function tableName()
+    {
+        return '{{%AMP_PERIOD}}';
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'ORDER_SN', 'PERIOD_NUM', 'BV'], 'required'],
+            [['PERIOD_NUM', 'BV'], 'number'],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '用户ID',
+            'ORDER_SN' => '订单号',
+            'PERIOD_NUM' => '周期',
+            'BV' => 'BV',
+        ];
+    }
+}

+ 2 - 0
common/models/Order.php

@@ -56,6 +56,7 @@ use Yii;
  * @property string $NOTE 备注说明
  * @property string COUNTRY_ID 国家ID
  * @property int CURRENCY_ID 币种ID
+ * @property int AUTO_MAINTENANCE AMP订单
  */
 class Order extends \common\components\ActiveRecord
 {
@@ -138,6 +139,7 @@ class Order extends \common\components\ActiveRecord
             'EMAIL' => 'Email',
             'COUNTRY_ID' => '国家ID',
             'CURRENCY_ID' => '币种ID',
+            'AUTO_MAINTENANCE' => 'AMP订单',
         ];
     }
     /*

+ 4 - 2
common/models/ShopGoods.php

@@ -27,6 +27,7 @@ namespace common\models;
  * @property int $DELETED_AT 删除时间
  * @property int $STATUS 状态
  * @property string $SORT 排序
+ * @property int $AUTO_MAINTENANCE AMP
  */
 class ShopGoods extends \common\components\ActiveRecord
 {
@@ -115,8 +116,8 @@ class ShopGoods extends \common\components\ActiveRecord
     public function rules()
     {
         return [
-            [['SELL_DISCOUNT','GOODS_NAME', 'CATE_ID','GIFT_TYPE', 'GOODS_NO', 'PRICE_PV','STORE_NUMS', 'SELL_TYPE', 'CATEGORY_TYPE', 'SELL_PRICE_STANDARD'], 'required'],
-            [['STORE_NUMS'], 'integer'],
+            [['SELL_DISCOUNT','GOODS_NAME', 'CATE_ID','GIFT_TYPE', 'GOODS_NO', 'PRICE_PV','STORE_NUMS', 'SELL_TYPE', 'CATEGORY_TYPE', 'SELL_PRICE_STANDARD', 'AUTO_MAINTENANCE'], 'required'],
+            [['STORE_NUMS', 'AUTO_MAINTENANCE'], 'integer'],
             [['PRICE_PV','POINT', 'CATEGORY_TYPE' ,'SELL_PRICE_STANDARD'], 'number'],
             [['ID','CATE_ID', 'GOODS_NO','GIFT_TYPE'], 'string', 'max' => 32],
             [['UNIT'], 'string', 'max' => 16],
@@ -154,6 +155,7 @@ class ShopGoods extends \common\components\ActiveRecord
             'UPDATED_AT' => '更新时间',
             'DELETED_AT' => '更新时间',
             'SORT' => '排序',
+            'AUTO_MAINTENANCE' => 'AMP'
         ];
     }
 

+ 298 - 10
common/models/forms/OrderForm.php

@@ -12,6 +12,7 @@ use common\helpers\user\Balance;
 use common\helpers\user\Cash;
 use common\helpers\user\Info;
 use common\libs\logging\operate\AdminOperate;
+use common\models\AmpPeriod;
 use common\models\Countries;
 use common\models\CurrencyConversions;
 use common\models\DealType;
@@ -62,6 +63,7 @@ class OrderForm extends Model
     public $lgaName;
     public $cityName;
     public $county;
+    public $autoMaintenance;
     public $detailaddress;
 
     private $_address;
@@ -152,6 +154,8 @@ class OrderForm extends Model
             'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress','decUserName'],
             // 管理员退款
             'adminRefund' => ['sn'],
+            // AMP
+            'autoMaintenanceOrder' => ['type', 'userName', 'payType', 'goodsId', 'goodsNum', 'remark', 'payPassword', 'consignee', 'acceptMobile', 'province', 'cityName', 'lgaName', 'detailaddress', 'decUserName'],
         ];
         return array_merge($parentScenarios, $customScenarios);
     }
@@ -1063,15 +1067,8 @@ class OrderForm extends Model
         $email = Info::getEmailByUserId($this->userName);
         $country = Countries::getById($countryId);
 
-        // 加入订单信息
-//        if($this->province!=1){
-//            $warehouse = Region::getWarehouseByCode($this->province);//仓库
-//            if(!$warehouse){
-//                throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
-//            }
-//        }else{
-            $warehouse = '01';
-//        }
+        $warehouse = '01';
+
         $ordNo = $this->_generateSn();
         $orderModel = new Order();
         $orderModel->SN = 'OS'.$ordNo;
@@ -1107,7 +1104,8 @@ class OrderForm extends Model
         $orderModel->EXCHANGE_RATE = $this->exchangeRate;
         $orderModel->COUNTRY_ID = $countryId;
         $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
-        $orderModel->DEC_USER_ID = $this->decUserName;;
+        $orderModel->DEC_USER_ID = $this->decUserName;
+        $orderModel->AUTO_MAINTENANCE = $this->autoMaintenance ?? 0;
         if(!$orderModel->save()){
             throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
         }
@@ -1126,6 +1124,11 @@ class OrderForm extends Model
         } else{
             Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => Yii::t('app', 'membersExchangePointPayment')]);
         }
+
+        if (($this->payType != 'prp') && ($this->autoMaintenance == 1)) {
+            $this->orderAutoMaintenance($orderModel);
+        }
+
         return $orderModel;
     }
 
@@ -1180,4 +1183,289 @@ class OrderForm extends Model
         }
         return $orderModel;
     }
+
+    /**
+     * AMP
+     * @return bool|null
+     * @throws Exception|\Throwable
+     */
+    public function autoMaintenanceSureOrder()
+    {
+        if (!$this->validate()) {
+            return null;
+        }
+
+        $ids = $this->goodsId;
+        $totalAmount = 0;
+        $totalPv = 0;
+        $totalRealPv = 0;
+        $totalAmountStandard = 0;
+        $this->autoMaintenance = 1;
+
+        $goodsType = ShopGoods::getGoodType();
+        $hasInstalment = 0;
+        $userId = Info::getUserIdByUserName($this->userName);
+        $user = User::getEnCodeInfo($userId);
+
+        $decUserID = Info::getUserIdByUserName($this->decUserName);
+        $stockist_user = User::getEnCodeInfo($decUserID);
+        if(!$stockist_user || $stockist_user['IS_DEC'] != 1){
+            throw new Exception(Yii::t('app', 'stockistDoesNotExist'));
+        }
+
+        // 报单中心汇率
+        $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['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);
+        if($loginUser['IS_DEC'] == 1){
+            if($decUserID != \Yii::$app->user->id){
+                throw new Exception(Yii::t('app', 'decUserNameIsWrong'));
+            }
+        }
+
+        foreach ($this->goodsNum as $k => $v) {
+            if ($v) {
+                $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
+                if (!$goods) {
+                    throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                }
+                if ($goods['AUTO_MAINTENANCE'] != 1) {
+                    throw new Exception(Yii::t('app', 'productsDoesNotAmp'));
+                }
+
+                $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'));
+                }
+
+                // 汇率
+                $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
+
+                if($goods['STORE_NUMS']>0){
+                    if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
+                        $discount = $goodsType[$goods['TYPE']]['discount'];
+                        $realPrice = $goodsNature['SELL_PRICE'] * $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;
+                        $realPv = $goods['PRICE_PV'] * $discount;
+                        $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
+                    }
+
+                    $currentPv = $goods['PRICE_PV'];
+                    $totalPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
+                    $totalRealPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
+                    $remainPv = 0;
+                    $this->_remainPv += 0;
+
+                    $totalAmount += $realPrice * intval($v);
+                    $totalAmountStandard += $realPriceStandard * intval($v);
+
+                    $this->_orderGoods[] = [
+                        'GOODS_ID' => $goods['ID'],
+                        'PRICE' => $goodsNature['SELL_PRICE'],
+                        'PV' => $this->payType == 'prp' ? 0 : $currentPv, // $goods['PRICE_PV'],
+                        'REAL_PRICE' => $realPrice,
+                        'REAL_PV' => $this->payType == 'prp' ? 0 : $realPv,
+                        'REMAIN_PV' => $this->payType == 'prp' ? 0 : $remainPv,
+                        'POINT' => $goods['POINT'],
+                        'BUY_NUMS' => intval($v),
+                        'SKU_CODE' => $goods['GOODS_NO'],
+                        'GOODS_TITLE' => $goods['GOODS_NAME'],
+                        'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
+                        'PAY_TYPE' => $this->payType,
+                        'EMAIL' => $this->email,
+                        'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
+                        'REAL_STANDARD_PRICE' => $realPriceStandard,
+                        'EXCHANGE_RATE' => $currencyRate,
+                        'TAX_RATE' => $goodsNature['TAX_RATE'],
+                    ];
+                }
+                if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
+                    if($v>1){ // 不可以购买多个
+                        throw new Exception(Yii::t('app', 'allowOnlyOne'));
+                    }
+
+                    $userStage = Instalment::getStage($userId);
+                    $userInstalmentInfo = Instalment::getInfo($userId);
+                    // 分期的总期数
+                    $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
+                    // 分期商品的期数不能大于总分期数限制
+                    if (intval($goods['INSTALMENT']) > $instalment) {
+                        throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
+                    }
+                    if ($userStage == $instalment){
+                        if ($goods['INSTALMENT'] != 1) {
+                            throw new Exception(Yii::t('app', 'canNotBuy'));
+                        }
+                    }else{
+                        if($userInstalmentInfo){
+                            if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
+                                throw new Exception(Yii::t('app', 'canNotBuy'));
+                            }
+                        }
+                        if($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
+                            throw new Exception(Yii::t('app', 'canNotBuy'));
+                        }
+                        if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
+                            throw new Exception(Yii::t('app', 'canNotBuy'));
+                        }
+                    }
+                    $hasInstalment = $goods['INSTALMENT'];
+                }
+            }
+        }
+
+        $sysConfig = Cache::getSystemConfig();
+        $ampDivideLine = (int)$sysConfig['ampBVCondition']['VALUE'];
+        if ($totalPv < $ampDivideLine) {
+            throw new Exception(Yii::t('app', 'ampOrderSubStandard', ['']));
+        }
+
+        // 运费模板
+        $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
+        // 运费
+        $freight = $freeTemplate['freight'] ?? 0;
+        // 普通商品免运费阈值
+        $freeShipping = $freeTemplate['free_shipping'] ?? 0;
+
+        $this->_decAmount = $totalAmount;
+        $this->_decPv = $this->payType == 'prp' ? 0 : $totalPv;
+        $this->_realPv = $this->payType == 'prp' ? 0 : $totalRealPv;
+        $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
+
+        $this->_payAmount = $this->_decAmount + $this->_freight;
+
+        $this->_decAmountStandard = $totalAmountStandard;
+        $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
+
+
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            $loginUserId = \Yii::$app->user->id;
+
+            //是否开启伞下会员限制
+            $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
+            if($isResaleUmbrella){
+                $userId = Info::getUserIdByUserName($this->userName);
+                $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
+                if(!$userNetwork){
+                    throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
+                }
+            }
+
+            if ($this->payType == 'prp') {
+                //看余额是否充足
+                $decCash = UserPerformance::getAmounts($loginUserId);
+            } else {
+                //看现金余额是否充足
+                $decCash = Cash::getAvailableBalance($loginUserId);
+            }
+
+            // 转换后的余额
+            $localCash = Tool::convertAmount($decCash, $decUserCurrencyRate, $currencyRate);
+            if ($localCash < $this->_decAmount){
+                throw new Exception(Yii::t('app', 'applicantPrpShort'), 400);
+            }
+
+            foreach ($this->goodsNum as $k => $v){
+                if ($v){
+                    $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
+                    if (!$goods) {
+                        throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                    }
+                    if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
+                        $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
+                        $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
+                        $data->STORE_NUMS = $goods_store_nums;
+                        $data->update();
+                        //下单后库存小于等于0 商品下架
+                        if($goods_store_nums <= 0){
+                            $data->STATUS = 0;
+                            $data->UPDATED_AT = Date::nowTime();
+                            $data->update();
+
+                        }
+                    }else{
+                        throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
+                    }
+                }
+            }
+
+            //写入订单
+            if (!$orderResult = $this->addUserOrder()) {
+                throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
+            }
+
+            if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
+                $instalmentModel = Instalment::findOne(['USER_ID'=>$userId]);
+                if(!$instalmentModel) {
+                    $instalmentModel = new Instalment();
+                }
+                $instalmentModel->USER_ID = $userId;
+                $instalmentModel->STAGE = $hasInstalment;
+                $instalmentModel->ORDER_TYPE = 'FX';
+                $instalmentModel->UPDATE_TIME = time();
+                $instalmentModel->save();
+            }
+
+            $transaction->commit();
+        }catch (\Exception $e){
+            $transaction->rollBack();
+            $this->addError('add', $e->getMessage());
+            return null;
+        }
+        return true;
+    }
+
+    private function orderAutoMaintenance($order)
+    {
+        try {
+            $sysConfig = Cache::getSystemConfig();
+            $divideLine = (int)$sysConfig['monthPcsPvFxCondition']['VALUE'];
+
+            $orderTotalBv = $order->PV;
+
+            if ($orderTotalBv <= $divideLine) {
+                return;
+            }
+
+            $lastAmpPeriod = AmpPeriod::find()
+                ->where(['USER_ID' => $order->USER_ID])
+                ->orderBy(['PERIOD_NUM' => SORT_DESC])
+                ->one();
+
+            $startPeriodNum = $lastAmpPeriod ? $lastAmpPeriod->PERIOD_NUM + 1 : $order->PERIOD_NUM;
+
+            $periodCount = floor($orderTotalBv / $divideLine);
+            $remainderBv = $orderTotalBv % $divideLine;
+
+            $ampPeriods = [];
+            for ($i = 1; $i <= $periodCount; $i++) {
+                $currentBv = $i < $periodCount ? $divideLine : ($divideLine + $remainderBv);
+                $ampPeriods[] = [
+                    'USER_ID' => $order->USER_ID,
+                    'ORDER_SN' => $order->SN,
+                    'PERIOD_NUM' => $startPeriodNum + $i - 1,
+                    'BV' => $currentBv,
+                ];
+            }
+
+            if (!empty($ampPeriods)) {
+                AmpPeriod::batchInsert($ampPeriods);
+            }
+        } catch (\Exception $e) {
+            // 记录日志或进行错误处理
+            \Yii::error('Order auto maintenance failed: ' . $e->getMessage());
+        }
+    }
 }

+ 7 - 3
common/models/forms/ShopGoodsForm.php

@@ -37,6 +37,7 @@ class ShopGoodsForm extends Model
     public $status;
     public $categoryType;
     public $nature;
+    public $autoMaintenance;
 
     private $_model;
 
@@ -54,7 +55,7 @@ class ShopGoodsForm extends Model
     {
         return [
             [['id','sellDiscount','giftType','sellType','goodsNo', 'goodsName', 'unit', 'pricePv', 'storeNums', 'content', 'sort','status','cover'], 'trim'],
-            [['goodsName','sellDiscount','giftType','goodsNo', 'storeNums','pricePv', 'sort','status', 'categoryType', 'sellPriceStandard', 'nature'], 'required'],
+            [['goodsName','sellDiscount','giftType','goodsNo', 'storeNums','pricePv', 'sort','status', 'categoryType', 'sellPriceStandard', 'nature', 'autoMaintenance'], 'required'],
             [['id'], 'required', 'on'=>'edit'],
             [['id'], 'exist', 'targetClass'=>ShopGoods::class, 'targetAttribute'=>'ID'],
             [['sellPrice','marketPrice','pricePv', 'sellPriceStandard'], 'price'],
@@ -85,6 +86,7 @@ class ShopGoodsForm extends Model
             'storeNums' => 'Inventory', // 库存
             'content' => 'Content',
             'listOrder' => 'Order',// 排序
+            'autoMaintenance' => 'Auto Maintenance',
         ];
     }
 
@@ -96,8 +98,8 @@ class ShopGoodsForm extends Model
     {
         $parentScenarios =  parent::scenarios();
         $customScenarios = [
-            'add' => ['goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','pricePv','storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'taxRate', 'taxAmount','pvSplit', 'nature'],
-            'edit' => ['id','goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','pricePv', 'storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'nature','pvSplit'],
+            'add' => ['goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','pricePv','storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'taxRate', 'taxAmount','pvSplit', 'nature', 'autoMaintenance'],
+            'edit' => ['id','goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','pricePv', 'storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'nature','pvSplit', 'autoMaintenance'],
             'changeStatus' => ['selectedIds', 'status'],
         ];
         return array_merge($parentScenarios, $customScenarios);
@@ -211,6 +213,7 @@ class ShopGoodsForm extends Model
             $shopGoods->CATE_ID = '1';
             $shopGoods->CREATED_AT = Date::nowTime();
             $shopGoods->CATEGORY_TYPE = $this->categoryType;
+            $shopGoods->AUTO_MAINTENANCE = $this->autoMaintenance;
             if (!$shopGoods->save()) {
                 throw new Exception(Form::formatErrorsForApi($shopGoods->getErrors()));
             }
@@ -271,6 +274,7 @@ class ShopGoodsForm extends Model
             $model->SORT = $this->sort;
             $model->UPDATED_AT = Date::nowTime();
             $model->CATEGORY_TYPE = $this->categoryType;
+            $model->AUTO_MAINTENANCE = $this->autoMaintenance;
             if (!$model->save()) {
                 throw new Exception(Form::formatErrorsForApi($model->getErrors()));
             }

+ 1 - 0
frontendApi/config/menu.php

@@ -41,6 +41,7 @@ return [
         'child'=>[
             ['name'=>'Member Welcome Pack', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'dec', 'routePath'=>'user/dec', 'show'=>1,  'wiki' => 'welcomePack',], // 会员报单
             ['name'=>'Member Repeat Purchase', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'reconsume', 'routePath'=>'shop/reconsume', 'show'=>1, 'wiki' => 'memberRepeatPurchase',],//会员复消
+            ['name'=>'Member Auto-Maintenance', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'reconsume', 'routePath'=>'shop/auto-maintenance', 'show'=>1, 'wiki' => 'memberAutoMaintenance',],//AMP
             ['name'=>'Member Upgrade', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'dec', 'routePath'=>'user/upgrade', 'show'=>1, /**'allow'=>'declarer',**/ 'wiki' => 'memberUpgrade',],//会员升级
             ['name'=>'Member Order', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'member-order', 'routePath'=>'shop/member-order', 'show'=>1, 'wiki' => 'memberOrder',],//会员订单
         ]

+ 2 - 0
frontendApi/config/urlManagerRules.php

@@ -96,6 +96,8 @@ return [
             'GET ba-dec-order-list' => 'ba-dec-order-list',
             'GET ba-dec-order-export/<orderSn>' => 'ba-dec-order-export',
             'POST sure-approach-reconsume-order' => 'sure-approach-reconsume-order',
+            'GET auto-maintenance' => 'auto-maintenance',
+            'POST reconsume-sure-order-sure-order' => 'reconsume-sure-order-sure-order',
         ],
     ],
     [

+ 52 - 0
frontendApi/modules/v1/controllers/ShopController.php

@@ -1856,4 +1856,56 @@ ORDER;
 
         return static::notice(['fileUrl' => $path, 'targetName' => $file_name]);
     }
+
+    /**
+     * AMP
+     */
+    public function actionAutoMaintenance()
+    {
+        // 会员信息
+        $user = User::findOneAsArray('ID=:ID', [':ID' => \Yii::$app->request->get('userId')]);
+        if (!$user) {
+            return static::notice(Yii::t('app', 'memberDoesNotExist'), 400);
+        }
+
+        $condition = ' AND STATUS=1 AND (FIND_IN_SET(2,GIFT_TYPE)>0 OR FIND_IN_SET(4,GIFT_TYPE)>0) AND N.COUNTRY_ID=:COUNTRY_ID AND AUTO_MAINTENANCE=1';
+        $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);
+    }
+
+    /**
+     * 确认订单
+     */
+    public function actionAutoMaintenanceSureOrder()
+    {
+        if (\Yii::$app->request->isPost) {
+            $formModel = new OrderForm();
+            $formModel->scenario = 'autoMaintenanceOrder';
+            $formModel->remark = Yii::t('app', 'autoMaintenance');
+            $post = \Yii::$app->request->post();
+            $post['type'] = DeclarationForm::TYPE_FX;
+            if ($formModel->load($post, '') && $formModel->autoMaintenanceSureOrder()) {
+                return static::notice(Yii::t('app', 'successfully'));
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
+            }
+        }
+    }
 }