From dac558895d1d44bf6bb85381ea873d4c7f318e6d Mon Sep 17 00:00:00 2001 From: Terry <2358269014@qq.com> Date: Sat, 9 May 2020 16:51:15 +0800 Subject: [PATCH] =?UTF-8?q?services=E6=96=B9=E6=B3=95=E5=8E=BB=E6=8E=89act?= =?UTF-8?q?ion=E5=BC=80=E5=A4=B4=E7=9A=84=E5=BD=A2=E5=BC=8F=EF=BC=8C?= =?UTF-8?q?=E5=85=A8=E9=83=A8=E6=94=B9=E4=B8=BApublic=E5=87=BD=E6=95=B0?= =?UTF-8?q?=EF=BC=8C=E4=BB=A5=E5=8F=8A=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E7=9A=84=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/Blog.php | 2 +- services/admin/Config.php | 2 + services/admin/Menu.php | 2 + services/admin/Role.php | 6 +- services/admin/RoleUrlKey.php | 6 +- services/admin/SystemLog.php | 11 +- services/admin/UrlKey.php | 7 +- services/admin/UserRole.php | 3 +- services/adminUser/AdminUser.php | 9 +- services/adminUser/UserLogin.php | 9 +- services/cart/Coupon.php | 49 ++--- services/cart/Info.php | 2 + services/cart/Quote.php | 82 +------ services/cart/QuoteItem.php | 11 +- services/category/CategoryMongodb.php | 93 ++++---- services/category/CategoryMysqldb.php | 49 ++--- services/category/Image.php | 10 +- services/category/Menu.php | 22 +- services/category/Product.php | 9 +- services/cms/Article.php | 22 +- services/cms/StaticBlock.php | 19 +- services/cms/article/ArticleMongodb.php | 6 + services/cms/article/ArticleMysqldb.php | 10 +- .../cms/staticblock/StaticBlockMongodb.php | 3 + .../cms/staticblock/StaticBlockMysqldb.php | 4 +- services/customer/Address.php | 66 ++---- services/customer/Facebook.php | 2 + services/customer/Google.php | 3 +- services/customer/Newsletter.php | 1 - .../customer/newsletter/NewsletterMongodb.php | 6 +- .../customer/newsletter/NewsletterMysqldb.php | 4 + services/email/Customer.php | 1 + .../widgets/customer/account/login/Body.php | 1 + services/extension/Administer.php | 7 + services/extension/Generate.php | 8 +- services/extension/RemoteService.php | 54 ++--- services/extension/UninstallInterface.php | 1 + services/extension/UpgradeInterface.php | 1 + services/helper/AR.php | 1 + services/helper/Appapi.php | 7 +- services/helper/Appserver.php | 41 +--- services/helper/Captcha.php | 2 + services/helper/Country.php | 2 - services/helper/Echart.php | 2 - services/helper/Errors.php | 4 +- services/helper/Format.php | 2 + services/helper/Wx.php | 10 +- services/helper/ZipFile.php | 4 + .../errorhandler/ErrorHandlerInterface.php | 2 +- .../errorhandler/ErrorHandlerMongodb.php | 3 + .../errorhandler/ErrorHandlerMysqldb.php | 3 + services/order/Item.php | 27 ++- services/page/Asset.php | 8 +- services/page/Breadcrumbs.php | 28 +-- services/page/Currency.php | 33 ++- services/page/Menu.php | 2 +- services/page/Message.php | 16 +- services/page/Newsletter.php | 3 - services/page/Theme.php | 16 +- services/page/Trace.php | 4 + services/page/Translate.php | 2 +- services/page/Widget.php | 42 ++-- services/payment/Alipay.php | 47 +--- services/payment/Paypal.php | 122 ++-------- services/payment/Wxpay.php | 56 ++--- services/payment/WxpayH5.php | 208 ++++-------------- services/payment/WxpayJsApi.php | 57 ++--- services/payment/WxpayMicro.php | 66 ++---- services/payment/wxpay/notify.php | 7 +- services/product/Attr.php | 35 +-- services/product/AttrGroup.php | 24 +- services/product/BestSell.php | 4 +- services/product/Brand.php | 8 +- services/product/Brandcategory.php | 5 +- services/product/Favorite.php | 2 +- services/product/Image.php | 25 +-- services/product/Info.php | 11 +- services/product/Price.php | 30 ++- services/product/ProductApi.php | 117 +--------- services/product/ProductMongodb.php | 102 ++------- services/product/ProductMysqldb.php | 115 ++-------- services/product/Review.php | 16 +- services/product/Stock.php | 50 +++-- services/product/attr/AttrMysqldb.php | 17 +- .../product/attrgroup/AttrGroupMysqldb.php | 11 +- services/product/favorite/FavoriteMongodb.php | 21 +- services/product/favorite/FavoriteMysqldb.php | 19 +- services/product/review/ReviewMongodb.php | 39 ++-- services/product/review/ReviewMysqldb.php | 41 ++-- services/product/viewLog/Db.php | 1 + services/product/viewLog/Mongodb.php | 3 +- services/product/viewLog/Session.php | 1 - services/search/MongoSearch.php | 61 ++--- services/search/MysqlSearch.php | 47 ++-- services/search/XunSearch.php | 51 ++--- services/url/Category.php | 44 +--- services/url/Rewrite.php | 24 +- services/url/rewrite/RewriteMongodb.php | 3 + services/url/rewrite/RewriteMysqldb.php | 7 +- 99 files changed, 744 insertions(+), 1620 deletions(-) diff --git a/services/Blog.php b/services/Blog.php index 52c260cc4..c70997327 100644 --- a/services/Blog.php +++ b/services/Blog.php @@ -17,7 +17,7 @@ */ class Blog extends Service { - public functiongetCategoryMenu() + public function getCategoryMenu() { } diff --git a/services/admin/Config.php b/services/admin/Config.php index 515614c31..e026956c3 100644 --- a/services/admin/Config.php +++ b/services/admin/Config.php @@ -103,11 +103,13 @@ public function save($one) $this->_model->attributes = $one; if ($this->_model->validate()) { $this->_model->save(); + return $this->_model[$primaryKey]; } else { $errors = $this->_model->errors; Yii::$service->helper->errors->addByModelErrors($errors); } + return null; } diff --git a/services/admin/Menu.php b/services/admin/Menu.php index 781dbc288..872a87963 100644 --- a/services/admin/Menu.php +++ b/services/admin/Menu.php @@ -50,12 +50,14 @@ public function getLeftMenuTreeHtml($treeArr='', $i=1){ foreach($treeArr as $node){ // 二次开发的过程中,如果fecshop后台的某些菜单想不显示,那么可以在配置中将active设置成false if (isset($node['active']) && $node['active'] === false) { + continue; } $name = Yii::$service->page->translate->__($node["label"]); $url_key = $node["url_key"]; $roleUrlKeys = $this->getRoleUrlKey(); if($url_key && (!isset($roleUrlKeys[$url_key]) || !$roleUrlKeys[$url_key])){ + continue; } if($i == 1){ diff --git a/services/admin/Role.php b/services/admin/Role.php index 2a6d6dcc9..c9084d523 100644 --- a/services/admin/Role.php +++ b/services/admin/Role.php @@ -20,7 +20,6 @@ */ class Role extends Service { - const ADMIN_ROLEIDS_RESOURCES = 'admin_roleids_resources'; public $numPerPage = 20; @@ -64,6 +63,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_roleModelName(); } } @@ -158,6 +158,7 @@ public function saveRoleAndResources($one){ $roleData['role_name'] = $one['role_name']; } else { Yii::$service->helper->errors->add('role name can not empty'); + return false; } if (isset($one['role_description'])) { @@ -196,6 +197,7 @@ protected function validateRoleName($one) } $one = $query->one(); if (!empty($one)) { + return false; } @@ -237,6 +239,7 @@ public function remove($ids) public function getCurrentRoleResources(){ if (!$this->_current_role_resources) { if (Yii::$app->user->isGuest) { + return []; } $user = Yii::$app->user->identity; @@ -257,6 +260,7 @@ public function getCurrentRoleResources(){ } } if (empty($role_ids)) { + return []; } diff --git a/services/admin/RoleUrlKey.php b/services/admin/RoleUrlKey.php index 140facbac..c8f0328e6 100644 --- a/services/admin/RoleUrlKey.php +++ b/services/admin/RoleUrlKey.php @@ -55,6 +55,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_modelName(); } } @@ -85,7 +86,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($one); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -147,8 +148,10 @@ public function repeatSaveRoleUrlKey($roleId, $url_key_ids){ $model->role_id = $roleId; $model->save(); } + return true; } + return false; } @@ -169,6 +172,7 @@ protected function validateUrlKeyRoleId($one) } $one = $query->one(); if (!empty($one)) { + return false; } diff --git a/services/admin/SystemLog.php b/services/admin/SystemLog.php index 3d29a1700..81bf8c2bb 100644 --- a/services/admin/SystemLog.php +++ b/services/admin/SystemLog.php @@ -39,7 +39,8 @@ public function init() list($this->_modelName, $this->_model) = Yii::mapGet($this->_modelName); } - public function getSystemLogModel(){ + public function getSystemLogModel() + { return $this->_model; } @@ -60,6 +61,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_modelName(); } } @@ -90,7 +92,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($one); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -100,6 +102,7 @@ public function coll($filter = '') # 保存系统日志。 public function save(){ if (!$this->enableLog) { + return false; } $systemLog = $this->_model; @@ -116,14 +119,16 @@ public function save(){ $systemLog->url = $url; $systemLog->url_key = $url_key; $systemLog->menu = $this->getMenuByUrlKey($url_key); - $systemLog->save(); + return $systemLog->save(); } } public function getMenuByUrlKey($url_key){ if(!$url_key) + return null; $menuArr = Yii::$service->admin->urlKey->getUrlKeyAndLabelArr(); + return isset($menuArr[$url_key]) ? $menuArr[$url_key] : null; } diff --git a/services/admin/UrlKey.php b/services/admin/UrlKey.php index 003769b9b..95455c2ff 100644 --- a/services/admin/UrlKey.php +++ b/services/admin/UrlKey.php @@ -62,6 +62,7 @@ public function getTags($translate = true){ } } } + return $this->_urlKeyTags[$key]; } @@ -82,6 +83,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_modelName(); } } @@ -112,7 +114,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($one); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -273,6 +275,7 @@ protected function validateUrlKey($one) } $one = $query->one(); if (!empty($one)) { + return false; } @@ -296,7 +299,6 @@ public function remove($ids) } $model->delete(); - // delete roleUrlKey Yii::$service->admin->roleUrlKey->removeByUrlKeyId($id); } } else { @@ -308,7 +310,6 @@ public function remove($ids) return false; } $model->delete(); - // delete roleUrlKey Yii::$service->admin->roleUrlKey->removeByUrlKeyId($id); } diff --git a/services/admin/UserRole.php b/services/admin/UserRole.php index 8253e4033..27d682ceb 100644 --- a/services/admin/UserRole.php +++ b/services/admin/UserRole.php @@ -54,6 +54,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_roleModelName(); } } @@ -85,7 +86,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($one); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), diff --git a/services/adminUser/AdminUser.php b/services/adminUser/AdminUser.php index ed5cee91f..98d7b18f9 100644 --- a/services/adminUser/AdminUser.php +++ b/services/adminUser/AdminUser.php @@ -67,10 +67,12 @@ public function getPrimaryKey() public function getActiveStatus(){ $model = $this->_model; + return $model::STATUS_ACTIVE; } public function getDeleteStatus(){ $model = $this->_model; + return $model::STATUS_DELETED; } @@ -117,7 +119,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($one); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -167,7 +169,6 @@ public function save($data) { return null; } - if ($this->_userFormModel[$primaryKey]) { if ($this->_userFormModel->validate()) { $this->_userFormModel->save(); @@ -237,10 +238,6 @@ public function remove($ids){ return $removeIds; } - - - - /** * @param $ids | Int Array * @return 得到相应用户的数组。 diff --git a/services/adminUser/UserLogin.php b/services/adminUser/UserLogin.php index f7a253cb7..a7fbbcb3a 100644 --- a/services/adminUser/UserLogin.php +++ b/services/adminUser/UserLogin.php @@ -34,7 +34,7 @@ public function init() * @param $data|array * 数组格式:['username'=>'xxx@xxx.com','password'=>'xxxx'] */ - public function actionLogin($data) + public function login($data) { $model = new $this->_adminUserLoginModelName(); $model->username = $data['username']; @@ -67,6 +67,7 @@ public function loginAndGetAccessToken($username, $password) $access_token_created_at = $identity->access_token_created_at; $timeout = Yii::$service->session->timeout; if ($access_token_created_at + $timeout > time()) { + return $accessToken; } } @@ -83,8 +84,10 @@ public function loginAndGetAccessToken($username, $password) $identity->access_token_created_at = time(); $identity->save(); $this->setHeaderAccessToken($identity->access_token); + return $identity->access_token; } + return null; } @@ -94,8 +97,10 @@ public function setHeaderAccessToken($accessToken) { if ($accessToken) { Yii::$app->response->getHeaders()->set('access-token', $accessToken); + return true; } + return false; } @@ -125,9 +130,11 @@ public function loginByAccessToken($type = null) $identity->access_token_created_at = time(); $identity->save(); } + return $identity; } else { $this->logoutByAccessToken(); + return false; } } diff --git a/services/cart/Coupon.php b/services/cart/Coupon.php index a3c92657f..ae31966f7 100644 --- a/services/cart/Coupon.php +++ b/services/cart/Coupon.php @@ -51,7 +51,7 @@ public function init() list($this->_couponUsageModelName, $this->_couponUsageModel) = Yii::mapGet($this->_couponUsageModelName); } - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return 'coupon_id'; } @@ -61,13 +61,15 @@ protected function actionGetPrimaryKey() * @return Object($this->_couponModel) * 通过id找到cupon的对象 */ - protected function actionGetByPrimaryKey($primaryKey) + public function getByPrimaryKey($primaryKey) { $one = $this->_couponModel->findOne($primaryKey); $primaryKey = $this->getPrimaryKey(); if ($one[$primaryKey]) { + return $one; } else { + return new $this->_couponModelName; } } @@ -77,7 +79,7 @@ protected function actionGetByPrimaryKey($primaryKey) * @param $coupon_id | Int * 通过customer_id 和 coupon_id得到 Coupon Usage Model. */ - protected function actionGetCouponUsageModel($customer_id = '', $coupon_id = '') + public function getCouponUsageModel($customer_id = '', $coupon_id = '') { if (!$this->_coupon_usage_model) { if (!$customer_id) { @@ -98,6 +100,7 @@ protected function actionGetCouponUsageModel($customer_id = '', $coupon_id = '') } } if ($this->_coupon_usage_model) { + return $this->_coupon_usage_model; } } @@ -106,7 +109,7 @@ protected function actionGetCouponUsageModel($customer_id = '', $coupon_id = '') * @param $coupon_code | String * 根据 coupon_code 得到 coupon model */ - protected function actionGetCouponModel($coupon_code = '') + public function getCouponModel($coupon_code = '') { if (!$this->_coupon_model) { if (!$coupon_code) { @@ -120,6 +123,7 @@ protected function actionGetCouponModel($coupon_code = '') } } if ($this->_coupon_model) { + return $this->_coupon_model; } } @@ -141,11 +145,12 @@ protected function actionGetCouponModel($coupon_code = '') * 'asArray' => true, * ] */ - protected function actionColl($filter = '') + public function coll($filter = '') { $query = $this->_couponModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); $coll = $query->all(); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -156,7 +161,7 @@ protected function actionColl($filter = '') * @param $one|array , save one data . * @return int 保存coupon成功后,返回保存的id。 */ - protected function actionSave($one) + public function save($one) { $time = time(); $primaryKey = $this->getPrimaryKey(); @@ -209,7 +214,7 @@ protected function actionSave($one) * 如果传入的是id数组,则删除多个 * 如果传入的是Int,则删除一个coupon */ - protected function actionRemove($ids) + public function remove($ids) { if (!$ids) { Yii::$service->helper->errors->add('remove id is empty'); @@ -264,12 +269,7 @@ protected function useCouponInit($coupon_code) $this->_customer_id = Yii::$app->user->identity->id; } } - // $this->getCouponUsageModel(); - // $this->getCouponModel(); - - // $this->_coupon_code $this->_coupon_code = $coupon_code; - $this->_useCouponInit = 1; } } @@ -288,6 +288,7 @@ protected function couponIsActive($isGetDiscount = false) // 未过期 if ($expiration_date > time()) { if ($isGetDiscount) { + return true; } $couponUsageModel = $this->getCouponUsageModel(); @@ -298,6 +299,7 @@ protected function couponIsActive($isGetDiscount = false) $users_per_customer = $couponModel['users_per_customer']; // 次数限制 if ($times_used < $users_per_customer) { + return true; } else { Yii::$service->helper->errors->add('The coupon has exceeded the maximum number of uses'); @@ -305,10 +307,9 @@ protected function couponIsActive($isGetDiscount = false) } else { Yii::$service->helper->errors->add('coupon is expired'); } - } else { - //Yii::$service->helper->errors->add("coupon is not exist"); } } + return false; } @@ -317,7 +318,7 @@ protected function couponIsActive($isGetDiscount = false) * @param $dc_price | Float 总价格 * 根据优惠券和总价格,计算出来打折后的价格。譬如原来10元,打八折后,是8元。 */ - protected function actionGetDiscount($coupon_code, $dc_price) + public function getDiscount($coupon_code, $dc_price) { $discount_cost = 0; $this->useCouponInit($coupon_code); @@ -329,10 +330,8 @@ protected function actionGetDiscount($coupon_code, $dc_price) //echo $conditions.'##'.$dc_price;;exit; if ($conditions <= $dc_price) { if ($type == $this->coupon_type_percent) { // 百分比 -// $base_discount_cost = $discount / 100 * $dc_price; $base_discount_cost = (1-$discount / 100) * $dc_price; } elseif ($type == $this->coupon_type_direct) { // 直接折扣 -// $base_discount_cost = $dc_price - $discount; $base_discount_cost = $discount; } $curr_discount_cost = Yii::$service->page->currency->getCurrentCurrencyPrice($base_discount_cost); @@ -377,6 +376,7 @@ protected function updateCouponUse($type) 'coupon_id' => $c_model['coupon_id'], ]; $result = $this->_couponModel->getDb()->createCommand($sql, $data)->execute(); + return true; } elseif ($type == 'cancel') { $couponModel = $this->getCouponModel(); @@ -408,7 +408,7 @@ protected function updateCouponUse($type) * 如果当前购物车没有使用优惠券,则检查优惠券是否可以使用 * 如果优惠券可以使用,则使用优惠券进行打折。更新购物车信息。 */ - protected function actionAddCoupon($coupon_code) + public function addCoupon($coupon_code) { $this->useCouponInit($coupon_code); @@ -426,22 +426,14 @@ protected function actionAddCoupon($coupon_code) if ($dc_price > $conditions) { // 更新购物侧的coupon 和优惠券的使用情况。 // 在service中不要出现事务等操作。在调用层使用。 - //$innerTransaction = Yii::$app->db->beginTransaction(); - //try { $set_status = Yii::$service->cart->quote->setCartCoupon($coupon_code); $up_status = $this->updateCouponUse('add'); if ($set_status && $up_status) { - //$innerTransaction->commit(); + return true; } else { Yii::$service->helper->errors->add('add coupon fail'); } - //Yii::$service->helper->errors->add('add coupon fail'); - //$innerTransaction->rollBack(); - //} catch (\Exception $e) { - //Yii::$service->helper->errors->add('add coupon fail'); - //$innerTransaction->rollBack(); - //} } else { Yii::$service->helper->errors->add('The coupon can not be used if the product amount in the shopping cart is less than {conditions} dollars', ['conditions' => $conditions]); } @@ -455,7 +447,7 @@ protected function actionAddCoupon($coupon_code) * @param $coupon_code | String * 取消优惠券 */ - protected function actionCancelCoupon($coupon_code) + public function cancelCoupon($coupon_code) { $this->useCouponInit($coupon_code); if ($this->_customer_id) { @@ -464,6 +456,7 @@ protected function actionCancelCoupon($coupon_code) $up_status = $this->updateCouponUse('cancel'); $cancel_status = Yii::$service->cart->quote->cancelCartCoupon($coupon_code); if ($up_status && $cancel_status) { + return true; } } diff --git a/services/cart/Info.php b/services/cart/Info.php index be0ee5f03..e93a0b680 100644 --- a/services/cart/Info.php +++ b/services/cart/Info.php @@ -139,9 +139,11 @@ public function getCustomOptionSku($item, $product) $product_custom_option = $product['custom_option']; $co_sku = Yii::$service->product->info->getProductCOSku($custom_option_arr, $product_custom_option); if ($co_sku) { + return $co_sku; } } + return ''; } } diff --git a/services/cart/Quote.php b/services/cart/Quote.php index 2e95e974e..11bb9500f 100644 --- a/services/cart/Quote.php +++ b/services/cart/Quote.php @@ -87,8 +87,6 @@ public function getCartId() $this->_cart_id = $cart_id; } } - - } return $this->_cart_id; @@ -115,7 +113,6 @@ public function updateGuestCart($address, $shipping_method, $payment_method) $cart->customer_address_city = $address['city']; $cart->customer_address_state = $address['state']; $cart->customer_address_zip = $address['zip']; - $cart->shipping_method = $shipping_method; $cart->payment_method = $payment_method; @@ -246,13 +243,12 @@ public function computeCartInfo($active_item_qty = null) * 设置cart_id类变量以及session中记录当前cartId的值 * Cart的session的超时时间由session组件决定。 */ - protected function actionSetCartId($cart_id) + public function setCartId($cart_id) { $this->_cart_id = $cart_id; if (!Yii::$service->store->isAppserver()) { Yii::$service->session->set(self::SESSION_CART_ID, $cart_id); } - } /** @@ -260,17 +256,16 @@ protected function actionSetCartId($cart_id) * 对于active的产品,在支付成功后,这些产品从购物车清楚 * 而对于noActive产品,这些产品并没有支付,因而在购物车中保留。 */ - protected function actionClearCart() + public function clearCart() { - //Yii::$service->session->remove(self::SESSION_CART_ID); - Yii::$service->cart->quoteItem->removeNoActiveItemsByCartId(); + return Yii::$service->cart->quoteItem->removeNoActiveItemsByCartId(); } /** * 初始化创建cart信息, * 在用户的第一个产品加入购物车时,会在数据库中创建购物车. */ - protected function actionCreateCart() + public function createCart() { $myCart = new $this->_cartModelName; $myCart->store = Yii::$service->store->currentStore; @@ -301,68 +296,6 @@ protected function actionCreateCart() $this->setCart($this->_cartModel->findOne($cart_id)); } - /** 该函数已经废弃 - * 购物车数据中是否含有address_id,address_id,是登录用户才会有的。 - */ - /* - public function hasAddressId() - { - $cart = $this->getCart(); - $address_id = $cart['customer_address_id']; - if ($address_id) { - return true; - } - } - */ - - /** - * 得到购物车中的用户地址信息. - * @deprecated 该函数已经废弃 - */ - /* - public function getCartAddress() - { - $email = ''; - $first_name = ''; - $last_name = ''; - if (!Yii::$app->user->isGuest) { - $identity = Yii::$app->user->identity; - $email = isset($identity['email']) ? $identity['email'] : ''; - $first_name = isset($identity['first_name']) ? $identity['first_name'] : ''; - $last_name = isset($identity['last_name']) ? $identity['last_name'] : ''; - } - $cart = $this->getCurrentCart(); - $customer_email = isset($cart['customer_email']) ? $cart['customer_email'] : ''; - $customer_firstname = isset($cart['customer_firstname']) ? $cart['customer_firstname'] : ''; - $customer_lastname = isset($cart['customer_lastname']) ? $cart['customer_lastname'] : ''; - $customer_telephone = isset($cart['customer_telephone']) ? $cart['customer_telephone'] : ''; - $customer_address_country = isset($cart['customer_address_country']) ? $cart['customer_address_country'] : ''; - $customer_address_state = isset($cart['customer_address_state']) ? $cart['customer_address_state'] : ''; - $customer_address_city = isset($cart['customer_address_city']) ? $cart['customer_address_city'] : ''; - $customer_address_zip = isset($cart['customer_address_zip']) ? $cart['customer_address_zip'] : ''; - $customer_address_street1 = isset($cart['customer_address_street1']) ? $cart['customer_address_street1'] : ''; - $customer_address_street2 = isset($cart['customer_address_street2']) ? $cart['customer_address_street2'] : ''; - - $customer_email = $customer_email ? $customer_email : $email; - $customer_firstname = $customer_firstname ? $customer_firstname : $first_name; - $customer_lastname = $customer_lastname ? $customer_lastname : $last_name; - - return [ - 'first_name' => $customer_firstname, - 'last_name' => $customer_lastname, - 'email' => $customer_email, - 'telephone' => $customer_telephone, - 'country' => $customer_address_country, - 'state' => $customer_address_state, - 'city' => $customer_address_city, - 'zip' => $customer_address_zip, - 'street1' => $customer_address_street1, - 'street2' => $customer_address_street2, - - ]; - } - */ - /** * @param $activeProduct | boolean , 是否只要active的产品 * @param $shipping_method | String 传递的货运方式 @@ -381,6 +314,7 @@ public function getCartInfo($activeProduct = true, $shipping_method = '', $count if (!isset($this->cartInfo[$cartInfoKey])) { $cart_id = $this->getCartId(); if (!$cart_id) { + return false; } $cart = $this->getCart(); @@ -389,6 +323,7 @@ public function getCartInfo($activeProduct = true, $shipping_method = '', $count // 购物车中active状态的产品个数 $items_count = $cart['items_count']; if ($items_count <=0 && $items_all_count <= 0) { + return false; } $coupon_code = $cart['coupon_code']; @@ -403,9 +338,6 @@ public function getCartInfo($activeProduct = true, $shipping_method = '', $count $product_total = $cart_product_info['product_total']; $base_product_total = $cart_product_info['base_product_total']; $product_qty_total = $cart_product_info['product_qty_total']; - //if (!$shipping_method) { - // $shipping_method = Yii::$service->shipping->getDefaultShippingMethod($country,$region,$product_weight); - //} if (is_array($products) && !empty($products)) { $currShippingCost = 0; $baseShippingCost = 0; @@ -501,6 +433,7 @@ public function getShippingCost($shipping_method = '', $weight = '', $country = public function getCouponCost($base_product_total, $coupon_code) { $dc_discount = Yii::$service->cart->coupon->getDiscount($coupon_code, $base_product_total); + return $dc_discount; } @@ -595,6 +528,7 @@ public function getCartByCustomerId($customer_id) if ($customer_id) { $one = $this->_cartModel->findOne(['customer_id' => $customer_id]); if ($one['cart_id']) { + return $one; } } diff --git a/services/cart/QuoteItem.php b/services/cart/QuoteItem.php index 122367e1c..125aca7ce 100644 --- a/services/cart/QuoteItem.php +++ b/services/cart/QuoteItem.php @@ -89,6 +89,7 @@ public function addItem($item, $product) $productValidate = Yii::$service->cart->info->checkProductBeforeAdd($checkItem, $product); if (!$productValidate) { + return false; } $item_one->active = $this->itemDefaultActiveStatus; @@ -101,6 +102,7 @@ public function addItem($item, $product) $checkItem = $item; $productValidate = Yii::$service->cart->info->checkProductBeforeAdd($checkItem, $product); if (!$productValidate) { + return false; } $item_one = new $this->_itemModelName; @@ -283,6 +285,7 @@ public function getCartProductInfo($activeProduct = true) foreach ($data as $one) { $active = $one['active']; if ($activeProduct && ($active != $this->activeStatus)) { + continue; } $product_id = $one['product_id']; @@ -349,7 +352,6 @@ public function getCartProductInfo($activeProduct = true) 'product_weight' => $product_weight, 'product_volume_weight' => $product_volume_weight, 'product_volume' => $product_volume, - ]; } } @@ -401,6 +403,7 @@ protected function getProductSpuOptions($productOb) } } } + return $custom_option_info_arr; } @@ -430,6 +433,7 @@ public function addOneItem($item_id) $productValidate = Yii::$service->cart->info->checkProductBeforeAdd($checkItem, $product); if (!$productValidate) { + return false; } $changeQty = Yii::$service->cart->getCartQty($product['package_number'], 1); @@ -446,6 +450,7 @@ public function addOneItem($item_id) ]; // 购物车数据加1 $this->sendTraceAddToCartInfoByApi($item); + return true; } } @@ -618,7 +623,6 @@ public function removeItemByCartId($cart_id = '') if ($cart_id) { $items = $this->_itemModel->deleteAll([ 'cart_id' => $cart_id, - //'item_id' => $item_id, ]); // 重新计算购物车的数量 Yii::$service->cart->quote->computeCartInfo(0); @@ -640,8 +644,7 @@ public function updateCartId($new_cart_id, $cart_id) ['cart_id' => $new_cart_id], // $attributes ['cart_id' => $cart_id] // $condition ); - // 重新计算购物车的数量 - //Yii::$service->cart->quote->computeCartInfo(); + return true; } diff --git a/services/category/CategoryMongodb.php b/services/category/CategoryMongodb.php index fbe9e11c9..3edda3491 100644 --- a/services/category/CategoryMongodb.php +++ b/services/category/CategoryMongodb.php @@ -37,8 +37,10 @@ public function init() public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_categoryModel->findOne($primaryKey); } else { + return new $this->_categoryModelName; } } @@ -58,8 +60,10 @@ public function getByUrlKey($urlKey) { if ($urlKey) { $urlKey = "/".trim($urlKey, "/"); + return $this->_categoryModel->findOne(['url_key' => $urlKey]); } else { + return new $this->_categoryModelName; } } @@ -78,6 +82,7 @@ public function getPrimaryKey() public function getCategoryEnableStatus() { $model = $this->_categoryModel; + return $model::STATUS_ENABLE; } @@ -87,6 +92,7 @@ public function getCategoryEnableStatus() public function getCategoryMenuShowStatus() { $model = $this->_categoryModel; + return $model::MENU_SHOW; } @@ -246,10 +252,10 @@ public function remove($ids) $deleteAll = false; } } + return $deleteAll; } else { $id = $ids; - //echo $id;exit; $model = $this->_categoryModel->findOne($id); if (isset($model[$this->getPrimaryKey()]) && !empty($model[$this->getPrimaryKey()])) { $url_key = $model['url_key']; @@ -262,6 +268,7 @@ public function remove($ids) return false; } } + return true; } @@ -327,6 +334,7 @@ protected function hasChildCategory($idVal) { $one = $this->_categoryModel->find()->asArray()->where(['parent_id'=>$idVal])->one(); if (!empty($one)) { + return true; } @@ -366,6 +374,7 @@ public function getAllParentInfo($parent_id) protected function getParentCategory($parent_id) { if ($parent_id === '0') { + return []; } $category = $this->_categoryModel->find()->asArray()->where(['_id' => new \MongoDB\BSON\ObjectId($parent_id)])->one(); @@ -373,7 +382,6 @@ protected function getParentCategory($parent_id) $currentUrlKey = $category['url_key']; $currentName = $category['name']; $currentId = (string) $category['_id']; - $currentCategory[] = [ '_id' => $currentId, 'name' => $currentName, @@ -384,6 +392,7 @@ protected function getParentCategory($parent_id) return array_merge($parentCategory, $currentCategory); } else { + return []; } } @@ -425,11 +434,6 @@ public function getFilterCategory($category_id, $parent_id) protected function getOneLevelCateChild($category) { - //'_id' => $currentId, - //'name' => $currentName, - //'url_key' => $currentUrlKey, - //$category['current'] = true; - //$data[0] = $category; $_id = $category['_id']; $name = $category['name']; $url_key = $category['url_key']; @@ -454,7 +458,6 @@ protected function getOneLevelCateChild($category) protected function getAllParentCate($allParent) { - //var_dump($allParent);exit; $d = $allParent; $data = []; if (is_array($allParent) && !empty($allParent)) { @@ -468,10 +471,7 @@ protected function getAllParentCate($allParent) 'status' => $this->getCategoryEnableStatus(), 'menu_show' => $this->getCategoryMenuShowStatus(), ])->all(); - //var_dump($cate); - //echo '$$$$$$$$$$'; if (is_array($cate) && !empty($cate)) { - //echo '**********'; foreach ($cate as $one) { $c_id = (string) $one['_id']; $data[$c_id] = [ @@ -479,8 +479,6 @@ protected function getAllParentCate($allParent) 'url_key' => $one['url_key'], 'parent_id' => $one['parent_id'], ]; - //echo $category_id; - //echo '&&&'.$c_id; if (($c_id == $category_id) && !empty($d)) { $data[$c_id]['child'] = $this->getAllParentCate($d); } @@ -493,6 +491,7 @@ protected function getAllParentCate($allParent) } } } + break; } } @@ -506,7 +505,6 @@ public function getChildCategory($category_id) { } protected function getChildCate($category_id) { - //echo $category_id; $data = $this->_categoryModel->find()->asArray()->where([ 'parent_id' => $category_id, 'status' => $this->getCategoryEnableStatus(), @@ -518,7 +516,6 @@ protected function getChildCate($category_id) $currentUrlKey = $one['url_key']; $currentName = $one['name']; $currentId = (string) $one['_id']; - $arr[$currentId] = [ //'_id' => $currentId, 'name' => $currentName, @@ -551,40 +548,38 @@ public function excelSave($one, $originUrlKey = 'catalog/category/index') return false; } - $model = $this->_categoryModel->findOne($primaryVal); - if (!isset($model[$this->getPrimaryKey()]) || !$model[$this->getPrimaryKey()]) { - $model = new $this->_categoryModelName; - $idV = $one[$this->getPrimaryKey()]; - //echo $this->getPrimaryKey(); - //echo $idV;exit; - $model[$this->getPrimaryKey()] = $idV ; - $model->created_at = time(); - $model->created_user_id = \fec\helpers\CUser::getCurrentUserId(); - } else { - $name =$model['name']; - $title = $model['title']; - $meta_keywords = $model['meta_keywords']; - $meta_description = $model['meta_description']; - $description = $model['description']; - //var_dump($title);var_dump($one['title']); - if (is_array($one['name']) && !empty($one['name'])) { - $one['name'] = array_merge((is_array($name) ? $name : []), $one['name']); - } - if (is_array($one['title']) && !empty($one['title'])) { - $one['title'] = array_merge((is_array($title) ? $title : []), $one['title']); - } - if (is_array($one['meta_keywords']) && !empty($one['meta_keywords'])) { - $one['meta_keywords'] = array_merge((is_array($meta_keywords) ? $meta_keywords : []), $one['meta_keywords']); - } - if (is_array($one['meta_description']) && !empty($one['meta_description'])) { - $one['meta_description'] = array_merge((is_array($meta_description) ? $meta_description : []), $one['meta_description']); - } - if (is_array($one['description']) && !empty($one['description'])) { - $one['description'] = array_merge((is_array($description) ? $description : []), $one['description']); - } + $model = $this->_categoryModel->findOne($primaryVal); + if (!isset($model[$this->getPrimaryKey()]) || !$model[$this->getPrimaryKey()]) { + $model = new $this->_categoryModelName; + $idV = $one[$this->getPrimaryKey()]; + //echo $this->getPrimaryKey(); + //echo $idV;exit; + $model[$this->getPrimaryKey()] = $idV ; + $model->created_at = time(); + $model->created_user_id = \fec\helpers\CUser::getCurrentUserId(); + } else { + $name =$model['name']; + $title = $model['title']; + $meta_keywords = $model['meta_keywords']; + $meta_description = $model['meta_description']; + $description = $model['description']; + //var_dump($title);var_dump($one['title']); + if (is_array($one['name']) && !empty($one['name'])) { + $one['name'] = array_merge((is_array($name) ? $name : []), $one['name']); } - //$parent_id = $model['parent_id']; - + if (is_array($one['title']) && !empty($one['title'])) { + $one['title'] = array_merge((is_array($title) ? $title : []), $one['title']); + } + if (is_array($one['meta_keywords']) && !empty($one['meta_keywords'])) { + $one['meta_keywords'] = array_merge((is_array($meta_keywords) ? $meta_keywords : []), $one['meta_keywords']); + } + if (is_array($one['meta_description']) && !empty($one['meta_description'])) { + $one['meta_description'] = array_merge((is_array($meta_description) ? $meta_description : []), $one['meta_description']); + } + if (is_array($one['description']) && !empty($one['description'])) { + $one['description'] = array_merge((is_array($description) ? $description : []), $one['description']); + } + } // 增加分类的级别字段level,从1级级别开始依次类推。 if ($parent_id === '0') { $model['level'] = 1; @@ -593,7 +588,6 @@ public function excelSave($one, $originUrlKey = 'catalog/category/index') if ($parent_level = $parent_model['level']) { $model['level'] = $parent_level + 1; } - } $model->updated_at = time(); unset($one['_id']); @@ -617,4 +611,5 @@ public function excelSave($one, $originUrlKey = 'catalog/category/index') return $model; } + } diff --git a/services/category/CategoryMysqldb.php b/services/category/CategoryMysqldb.php index 76dceafb9..fd8b430cb 100644 --- a/services/category/CategoryMysqldb.php +++ b/services/category/CategoryMysqldb.php @@ -34,11 +34,9 @@ class CategoryMysqldb extends Service implements CategoryInterface 'name', 'menu_custom', 'description', - 'title', 'meta_keywords', 'meta_description', - ]; public function init() @@ -46,13 +44,13 @@ public function init() parent::init(); list($this->_categoryModelName, $this->_categoryModel) = Yii::mapGet($this->_categoryModelName); list($this->_categoryProductModelName, $this->_categoryProductModel) = \Yii::mapGet($this->_categoryProductModelName); - } // 保存的数据进行serialize序列化 protected function serializeSaveData($one) { if (!is_array($one) && !is_object($one)) { + return $one; } foreach ($one as $k => $v) { @@ -60,12 +58,14 @@ protected function serializeSaveData($one) $one[$k] = serialize($v); } } + return $one; } // 保存的数据进行serialize序列化 protected function unserializeData($one) { if (!is_array($one) && !is_object($one)) { + return $one; } foreach ($one as $k => $v) { @@ -73,6 +73,7 @@ protected function unserializeData($one) $one[$k] = unserialize($v); } } + return $one; } @@ -83,8 +84,10 @@ public function getByPrimaryKey($primaryKey) { if ($primaryKey) { $one = $this->_categoryModel->findOne($primaryKey); + return $this->unserializeData($one) ; } else { + return new $this->_categoryModelName; } } @@ -107,8 +110,10 @@ public function getByUrlKey($urlKey) if ($urlKey) { $urlKey = "/".trim($urlKey, "/"); $one = $this->_categoryModel->findOne(['url_key' => $urlKey]); + return $this->unserializeData($one) ; } else { + return new $this->_categoryModelName; } } @@ -127,6 +132,7 @@ public function getPrimaryKey() public function getCategoryEnableStatus() { $model = $this->_categoryModel; + return $model::STATUS_ENABLE; } @@ -136,6 +142,7 @@ public function getCategoryEnableStatus() public function getCategoryMenuShowStatus() { $model = $this->_categoryModel; + return $model::MENU_SHOW; } @@ -162,6 +169,7 @@ public function coll($filter = '') foreach ($coll as $one) { $arr[] = $this->unserializeData($one) ; } + return [ 'coll' => $arr, 'count'=> $query->limit(null)->offset(null)->count(), @@ -214,8 +222,6 @@ public function save($one, $originUrlKey = 'catalog/category/index') $model = new $this->_categoryModelName; $model->created_at = time(); $model->created_user_id = \fec\helpers\CUser::getCurrentUserId(); - //$primaryVal = new \MongoDB\BSON\ObjectId(); - //$model->{$this->getPrimaryKey()} = $primaryVal; $parent_id = $one['parent_id']; } // 增加分类的级别字段level,从1级级别开始依次类推。 @@ -270,19 +276,16 @@ public function sync($arr) $model = new $this->_categoryModelName; $model->created_at = time(); } - $model->origin_mongo_id = $origin_mongo_id; $model->origin_mongo_parent_id = $origin_mongo_parent_id; $arr = $this->serializeSaveData($arr); $saveStatus = Yii::$service->helper->ar->save($model, $arr); - $originUrl = $originUrlKey.'?'.$this->getPrimaryKey() .'='. $model->id; $originUrlKey = isset($model['url_key']) ? $model['url_key'] : ''; $defaultLangTitle = Yii::$service->fecshoplang->getDefaultLangAttrVal($arr['name'], 'name'); $urlKey = Yii::$service->url->saveRewriteUrlKeyByStr($defaultLangTitle, $originUrl, $originUrlKey); $model->url_key = $urlKey; - $model->save(); - + return $model->save(); } /** @@ -310,11 +313,10 @@ public function remove($ids) $this->removeCategoryProductRelationByCategoryId($id); } else { Yii::$service->helper->errors->add("Category Remove Errors:ID:{id} is not exist.", ['id' => $id]); - $deleteAll = false; } - } + return $deleteAll; } else { $id = $ids; @@ -330,9 +332,9 @@ public function remove($ids) return false; } - // delete category product relation $this->removeCategoryProductRelationByCategoryId($id); } + return true; } @@ -376,7 +378,6 @@ public function getTreeArr($rootCategoryId = '', $lang = '', $appserver=false, $ ->where($where) ->orderBy($orderBy) ->all(); - //var_dump($categorys);exit; $idKey = $this->getPrimaryKey(); if (!empty($categorys)) { foreach ($categorys as $cate) { @@ -391,8 +392,6 @@ public function getTreeArr($rootCategoryId = '', $lang = '', $appserver=false, $ if ($appserver) { $arr[$idVal]['url'] = '/catalog/category/'.$idVal; } - //echo $arr[$idVal]['name']; - if ($this->hasChildCategory($idVal)) { $arr[$idVal]['child'] = $this->getTreeArr($idVal, $lang, $appserver, $level+1); } @@ -406,6 +405,7 @@ public function hasChildCategory($idVal) { $one = $this->_categoryModel->find()->asArray()->where(['parent_id'=>$idVal])->one(); if (!empty($one)) { + return true; } @@ -446,6 +446,7 @@ public function getAllParentInfo($parent_id) protected function getParentCategory($parent_id) { if ($parent_id === 0) { + return []; } $category = $this->_categoryModel->find()->asArray()->where(['id' => $parent_id])->one(); @@ -465,6 +466,7 @@ protected function getParentCategory($parent_id) return array_merge($parentCategory, $currentCategory); } else { + return []; } } @@ -507,11 +509,6 @@ public function getFilterCategory($category_id, $parent_id) protected function getOneLevelCateChild($category) { - //'id' => $currentId, - //'name' => $currentName, - //'url_key' => $currentUrlKey, - //$category['current'] = true; - //$data[0] = $category; $id = $category['_id']; $name = $category['name']; $url_key = $category['url_key']; @@ -537,7 +534,6 @@ protected function getOneLevelCateChild($category) protected function getAllParentCate($allParent) { - //var_dump($allParent);exit; $d = $allParent; $data = []; if (is_array($allParent) && !empty($allParent)) { @@ -551,10 +547,7 @@ protected function getAllParentCate($allParent) 'status' => $this->getCategoryEnableStatus(), 'menu_show' => $this->getCategoryMenuShowStatus(), ])->all(); - //var_dump($cate); - //echo '$$$$$$$$$$'; if (is_array($cate) && !empty($cate)) { - //echo '**********'; foreach ($cate as $one) { $one =$this->unserializeData($one) ; $c_id = $one['id']; @@ -563,8 +556,6 @@ protected function getAllParentCate($allParent) 'url_key' => $one['url_key'], 'parent_id' => $one['parent_id'], ]; - //echo $category_id; - //echo '&&&'.$c_id; if (($c_id == $category_id) && !empty($d)) { $data[$c_id]['child'] = $this->getAllParentCate($d); } @@ -577,6 +568,7 @@ protected function getAllParentCate($allParent) } } } + break; } } @@ -592,7 +584,6 @@ public function getChildCategory($category_id) { protected function getChildCate($category_id) { - //echo $category_id; $data = $this->_categoryModel->find()->asArray()->where([ 'parent_id' => $category_id, 'status' => $this->getCategoryEnableStatus(), @@ -673,9 +664,6 @@ public function excelSave($one, $originUrlKey = 'catalog/category/index') $one['description'] = array_merge((is_array($description) ? $description : []), $one['description']); } } - //$parent_id = $model['parent_id']; - - // 增加分类的级别字段level,从1级级别开始依次类推。 if ($parent_id == 0) { $model['level'] = 1; @@ -697,7 +685,6 @@ public function excelSave($one, $originUrlKey = 'catalog/category/index') if (!in_array($one['status'], $allowStatusArr)) { $one['status'] = $model::STATUS_ENABLE; } - //var_dump($one);exit; $one = $this->serializeSaveData($one); $saveStatus = Yii::$service->helper->ar->save($model, $one); $primaryVal = $model->id; diff --git a/services/category/Image.php b/services/category/Image.php index 70fb22922..129480e92 100644 --- a/services/category/Image.php +++ b/services/category/Image.php @@ -44,7 +44,7 @@ class Image extends Service /** * 得到保存分类图片所在相对根目录的url路径. */ - protected function actionGetBaseUrl() + public function getBaseUrl() { return Yii::$service->image->GetImgUrl($this->imageFloder, 'common'); } @@ -52,7 +52,7 @@ protected function actionGetBaseUrl() /** * 得到保存分类图片所在相对根目录的文件夹路径. */ - protected function actionGetBaseDir() + public function getBaseDir() { return Yii::$service->image->GetImgDir($this->imageFloder, 'common'); } @@ -60,7 +60,7 @@ protected function actionGetBaseDir() /** * 通过分类图片的相对路径得到产品图片的url. */ - protected function actionGetUrl($str) + public function getUrl($str) { return Yii::$service->image->GetImgUrl($this->imageFloder.$str, 'common'); } @@ -68,7 +68,7 @@ protected function actionGetUrl($str) /** * 通过分类图片的相对路径得到分类图片的绝对路径. */ - protected function actionGetDir($str) + public function getDir($str) { return Yii::$service->image->GetImgDir($this->imageFloder.$str, 'common'); } @@ -80,7 +80,7 @@ protected function actionGetDir($str) * return , if success ,return image saved relative file path , like '/b/i/big.jpg' * if fail, reutrn false; */ - protected function actionSaveCategoryUploadImg($FILE) + public function saveCategoryUploadImg($FILE) { Yii::$service->image->imageFloder = $this->imageFloder; Yii::$service->image->allowImgType = $this->allowImgType; diff --git a/services/category/Menu.php b/services/category/Menu.php index 1ce9e761b..fd07fd0c7 100644 --- a/services/category/Menu.php +++ b/services/category/Menu.php @@ -21,29 +21,16 @@ class Menu extends Service { public $rootCategoryId = '0'; - - //protected $_categoryModelName = '\fecshop\models\mongodb\Category'; - - //protected $_categoryModel; - - //public function init() - //{ - //parent::init(); - //list($this->_categoryModelName, $this->_categoryModel) = Yii::mapGet($this->_categoryModelName); - //} - /** * @param $parentId | int * 得到分类的目录信息 */ - protected function actionGetCategoryMenuArr($parentId = '') + public function getCategoryMenuArr($parentId = '') { - //$model = $this->_categoryModel; $arr = []; if (!$parentId) { $parentId = $this->rootCategoryId; } - $categoryPrimaryKey = Yii::$service->category->getPrimaryKey(); $orderBy = ['sort_order' => SORT_DESC]; $filter = [ @@ -59,13 +46,6 @@ protected function actionGetCategoryMenuArr($parentId = '') ]; $collData = Yii::$service->category->coll($filter); $data = $collData['coll']; - //$data = $this->_categoryModel->find()->asArray()->select([ - // '_id', 'parent_id', 'name', 'url_key', 'menu_custom', - //])->where([ - // 'parent_id' => $parentId, - // 'status' => $model::STATUS_ENABLE, - // 'menu_show' => $model::MENU_SHOW, - //])->all(); if (is_array($data) && !empty($data)) { foreach ($data as $category) { $categoryOne = [ diff --git a/services/category/Product.php b/services/category/Product.php index a1dca55fa..015f66d86 100644 --- a/services/category/Product.php +++ b/services/category/Product.php @@ -40,7 +40,7 @@ class Product extends Service * ] * 通过搜索条件得到当类下的产品。 */ - protected function actionColl($filter) + public function coll($filter) { $category_id = isset($filter['category_id']) ? $filter['category_id'] : ''; if (!$category_id) { @@ -71,14 +71,14 @@ protected function actionColl($filter) /** * @param $filter | Array 和上面的函数 actionColl($filter) 类似。 */ - protected function actionGetFrontList($filter) + public function getFrontList($filter) { $filter['group'] = '$spu'; $coll = Yii::$service->product->getFrontCategoryProducts($filter); - $collection = $coll['coll']; $count = $coll['count']; $arr = $this->convertToCategoryInfo($collection); + return [ 'coll' => $arr, 'count'=> $count, @@ -88,7 +88,7 @@ protected function actionGetFrontList($filter) /** * 将service取出来的数据,处理一下,然后前端显示。 */ - protected function actionConvertToCategoryInfo($collection) + public function convertToCategoryInfo($collection) { $arr = []; $defaultImg = Yii::$service->product->image->defautImg(); @@ -139,6 +139,7 @@ protected function actionConvertToCategoryInfo($collection) protected function getPrices($price, $special_price, $special_from, $special_to) { if (Yii::$service->product->price->specialPriceisActive($price, $special_price, $special_from, $special_to)) { + return [$price, $special_price]; } diff --git a/services/cms/Article.php b/services/cms/Article.php index acdc4c38c..65510d1bb 100644 --- a/services/cms/Article.php +++ b/services/cms/Article.php @@ -50,18 +50,10 @@ public function init() $this->_article = new $currentService(); } - /** - * Get Url by article's url key. - */ - //public function getUrlByPath($urlPath){ - //return Yii::$service->url->getHttpBaseUrl().'/'.$urlKey; - //return Yii::$service->url->getUrlByPath($urlPath); - //} - /** * get artile's primary key. */ - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return $this->_article->getPrimaryKey(); } @@ -69,7 +61,7 @@ protected function actionGetPrimaryKey() /** * get artile model by primary key. */ - protected function actionGetByPrimaryKey($primaryKey) + public function getByPrimaryKey($primaryKey) { return $this->_article->getByPrimaryKey($primaryKey); } @@ -78,7 +70,7 @@ protected function actionGetByPrimaryKey($primaryKey) * @param $urlKey | String , 对应表的url_key字段 * 根据url_key 查询得到article model */ - protected function actionGetByUrlKey($urlKey) + public function getByUrlKey($urlKey) { return $this->_article->getByUrlKey($urlKey); } @@ -86,7 +78,7 @@ protected function actionGetByUrlKey($urlKey) /** * 得到category model的全名. */ - protected function actionGetModelName() + public function getModelName() { return get_class($this->_article); } @@ -107,7 +99,7 @@ protected function actionGetModelName() * 'asArray' => true, * ] */ - protected function actionColl($filter = '') + public function coll($filter = '') { return $this->_article->coll($filter); } @@ -117,12 +109,12 @@ protected function actionColl($filter = '') * @param $originUrlKey|string , article origin url key. * save $data to cms model,then,add url rewrite info to system service urlrewrite. */ - protected function actionSave($one, $originUrlKey) + public function save($one, $originUrlKey) { return $this->_article->save($one, $originUrlKey); } - protected function actionRemove($ids) + public function remove($ids) { return $this->_article->remove($ids); } diff --git a/services/cms/StaticBlock.php b/services/cms/StaticBlock.php index c8a9377a5..6c99824b4 100644 --- a/services/cms/StaticBlock.php +++ b/services/cms/StaticBlock.php @@ -51,20 +51,13 @@ public function init() } $currentService = $this->getStorageService($this); $this->_static_block = new $currentService(); - /* - if ($this->storage == 'mongodb') { - $this->_static_block = new StaticBlockMongodb(); - } elseif ($this->storage == 'mysqldb') { - $this->_static_block = new StaticBlockMysqldb(); - } - */ } /** * get store static block content by identify * example cms->staticblock->getStoreContentByIdentify('home-big-img','appfront') ?>. */ - protected function actionGetStoreContentByIdentify($identify, $app = 'common') + public function getStoreContentByIdentify($identify, $app = 'common') { $staticBlock = $this->_static_block->getByIdentify($identify); $content = isset($staticBlock['content'])?$staticBlock['content']:''; @@ -98,7 +91,7 @@ protected function getStaticBlockVariableArr($app) /** * get artile's primary key. */ - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return $this->_static_block->getPrimaryKey(); } @@ -106,7 +99,7 @@ protected function actionGetPrimaryKey() /** * get artile model by primary key. */ - protected function actionGetByPrimaryKey($primaryKey) + public function getByPrimaryKey($primaryKey) { return $this->_static_block->getByPrimaryKey($primaryKey); } @@ -127,7 +120,7 @@ protected function actionGetByPrimaryKey($primaryKey) * 'asArray' => true, * ] */ - protected function actionColl($filter = '') + public function coll($filter = '') { return $this->_static_block->coll($filter); } @@ -136,12 +129,12 @@ protected function actionColl($filter = '') * @param $one|array , save one data . * save $data to cms model,then,add url rewrite info to system service urlrewrite. */ - protected function actionSave($one) + public function save($one) { return $this->_static_block->save($one); } - protected function actionRemove($ids) + public function remove($ids) { return $this->_static_block->remove($ids); } diff --git a/services/cms/article/ArticleMongodb.php b/services/cms/article/ArticleMongodb.php index 467277238..fef54bf45 100644 --- a/services/cms/article/ArticleMongodb.php +++ b/services/cms/article/ArticleMongodb.php @@ -41,8 +41,10 @@ public function getPrimaryKey() public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_articleModel->findOne($primaryKey); } else { + return new $this->_articleModelName; } } @@ -56,9 +58,11 @@ public function getByUrlKey($urlKey) if ($urlKey) { $model = $this->_articleModel->findOne(['url_key' => '/'.$urlKey]); if (isset($model['url_key'])) { + return $model; } } + return false; } @@ -120,6 +124,7 @@ public function save($one, $originUrlKey) $this->initStatus($model); $model->save(); $model['_id'] = (string)$model['_id']; + return $model->attributes; } @@ -160,6 +165,7 @@ public function remove($ids) $deleteAll = false; } } + return $deleteAll; } else { $id = $ids; diff --git a/services/cms/article/ArticleMysqldb.php b/services/cms/article/ArticleMysqldb.php index f20e30bd5..d52a78848 100644 --- a/services/cms/article/ArticleMysqldb.php +++ b/services/cms/article/ArticleMysqldb.php @@ -60,6 +60,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_articleModelName(); } } @@ -77,10 +78,11 @@ public function getByUrlKey($urlKey) $model['title'] = unserialize($model['title']); $model['meta_keywords'] = unserialize($model['meta_keywords']); $model['meta_description'] = unserialize($model['meta_description']); - //var_dump($model); + return $model; } } + return false; } @@ -111,7 +113,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($coll); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -146,7 +148,6 @@ public function save($one, $originUrlKey) $one[$attrName] = serialize($one[$attrName]); } } - unset($one['id']); $primaryKey = $this->getPrimaryKey(); $saveStatus = Yii::$service->helper->ar->save($model, $one); @@ -154,9 +155,7 @@ public function save($one, $originUrlKey) $originUrl = $originUrlKey.'?'.$this->getPrimaryKey() .'='. $primaryVal; $originUrlKey = isset($one['url_key']) ? $one['url_key'] : ''; - $urlKey = Yii::$service->url->saveRewriteUrlKeyByStr($defaultLangTitle, $originUrl, $originUrlKey); - $model->url_key = $urlKey; $this->initStatus($model); $model->save(); @@ -165,6 +164,7 @@ public function save($one, $originUrlKey) $model['title'] = unserialize($model['title']); $model['meta_keywords'] = unserialize($model['meta_keywords']); $model['meta_description'] = unserialize($model['meta_description']); + return $model->attributes; } diff --git a/services/cms/staticblock/StaticBlockMongodb.php b/services/cms/staticblock/StaticBlockMongodb.php index 86b6b84e5..bd6b142d3 100644 --- a/services/cms/staticblock/StaticBlockMongodb.php +++ b/services/cms/staticblock/StaticBlockMongodb.php @@ -41,8 +41,10 @@ public function getPrimaryKey() public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_staticBlockModel->findOne($primaryKey); } else { + return new $this->_staticBlockModelName(); } } @@ -128,6 +130,7 @@ protected function validateIdentify($one) $one = $query->one(); if (!empty($one)) { + return false; } diff --git a/services/cms/staticblock/StaticBlockMysqldb.php b/services/cms/staticblock/StaticBlockMysqldb.php index 654470575..afa8a78a6 100644 --- a/services/cms/staticblock/StaticBlockMysqldb.php +++ b/services/cms/staticblock/StaticBlockMysqldb.php @@ -57,6 +57,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_staticBlockModelName(); } } @@ -102,7 +103,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($one); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -160,6 +161,7 @@ protected function validateIdentify($one) } $one = $query->one(); if (!empty($one)) { + return false; } diff --git a/services/customer/Address.php b/services/customer/Address.php index b57cf49b3..e8f11d9ea 100644 --- a/services/customer/Address.php +++ b/services/customer/Address.php @@ -37,7 +37,7 @@ public function init() list($this->_addressModelName, $this->_addressModel) = \Yii::mapGet($this->_addressModelName); } - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return 'address_id'; } @@ -47,13 +47,15 @@ protected function actionGetPrimaryKey() * @return Object(MyCoupon) * 通过id找到customer address的对象 */ - protected function actionGetByPrimaryKey($primaryKey) + public function getByPrimaryKey($primaryKey) { $one = $this->_addressModel->findOne($primaryKey); $primaryKey = $this->getPrimaryKey(); if ($one[$primaryKey]) { + return $one; } else { + return new $this->_addressModelName(); } } @@ -64,7 +66,7 @@ protected function actionGetByPrimaryKey($primaryKey) * 在这里在主键查询的同时,加入customer_id,这样查询的肯定是这个用户的, * 这样就防止有的用户去查询其他用户的address信息。 */ - protected function actionGetAddressByIdAndCustomerId($address_id, $customer_id) + public function getAddressByIdAndCustomerId($address_id, $customer_id) { $primaryKey = $this->getPrimaryKey(); $one = $this->_addressModel->findOne([ @@ -72,8 +74,10 @@ protected function actionGetAddressByIdAndCustomerId($address_id, $customer_id) 'customer_id' => $customer_id, ]); if ($one[$primaryKey]) { + return $one; } else { + return false; } } @@ -95,7 +99,7 @@ protected function actionGetAddressByIdAndCustomerId($address_id, $customer_id) * 'asArray' => true, * ] */ - protected function actionColl($filter = '') + public function coll($filter = '') { $query = $this->_addressModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); @@ -111,7 +115,7 @@ protected function actionColl($filter = '') * @return Array * 得到当前用户的所有货运地址数组 */ - protected function actionCurrentAddressList() + public function currentAddressList() { $arr = []; if (!Yii::$app->user->isGuest) { @@ -145,7 +149,6 @@ protected function actionCurrentAddressList() $area = $one['area']; $country = Yii::$service->helper->country->getCountryNameByKey($one['country']); $state = Yii::$service->helper->country->getStateByContryCode($one['country'],$one['state']); - $address_info = [ 'address_id' => $address_id, 'first_name' => $first_name, @@ -159,10 +162,6 @@ protected function actionCurrentAddressList() 'zip' => $zip, 'area' => $area, ]; - - //$state = Yii::$service->helper->country->getStateByContryCode($one['country'],$one['state']); - - $str = $first_name.' '.$last_name.' '.$email.' '. $street1.' '.$street2.' '.$city.' '.$state.' '.$country.' '. $zip.' '.$telephone; @@ -179,6 +178,7 @@ protected function actionCurrentAddressList() // 如果没有默认的地址,则取第一个当默认 foreach ($arr as $k=>$v) { $arr[$k]['is_default'] = 1; + break; } } @@ -193,7 +193,7 @@ protected function actionCurrentAddressList() * @param $one|array , 保存的address数组 * @return int 返回保存的 address_id 的值。 */ - protected function actionSave($one) + public function save($one) { if (!is_array($one) || empty($one)) { Yii::$service->helper->errors->add('address data is empty'); @@ -220,10 +220,10 @@ protected function actionSave($one) // 保存地址。 $model = Yii::$service->helper->ar->save($model, $one); if (!$model) { + return false; } } else { - $errors = $model->errors; Yii::$service->helper->errors->addByModelErrors($errors); @@ -254,7 +254,7 @@ protected function actionSave($one) * 删除address的同时,删除掉购物车中的address_id * 删除address的同时,如果删除的是default address,那么重新找出来一个address作为default address并保存到表中。 */ - protected function actionRemove($ids, $customer_id) + public function remove($ids, $customer_id) { if (!$ids) { Yii::$service->helper->errors->add('remove id is empty'); @@ -273,10 +273,6 @@ protected function actionRemove($ids, $customer_id) Yii::$service->helper->errors->add('remove address is not current customer address'); } } - //} else { - // $this->removeCartAddress($model['customer_id'], $id); - // $model->delete(); - //} } else { Yii::$service->helper->errors->add('Address Remove Errors:ID {id} is not exist', ['id' => $id]); @@ -295,10 +291,6 @@ protected function actionRemove($ids, $customer_id) Yii::$service->helper->errors->add('remove address is not current customer address'); } } - //} else { - // $this->removeCartAddress($model['customer_id'], $id); - // $model->delete(); - //} } else { Yii::$service->helper->errors->add('Address Remove Errors:ID:{id} is not exist', ['id'=> $id]); @@ -362,7 +354,6 @@ public function setDefault($customer_id, $address_id) $address_one->is_default = 1; $address_one->updated_at = time(); $address_one->save(); - // 将其他的设置成2 $this->_addressModel->updateAll( ['is_default'=>2], // $attributes @@ -374,7 +365,6 @@ public function setDefault($customer_id, $address_id) ); return true; - } public function getDefualtAddressId($customer_id = '') @@ -384,46 +374,20 @@ public function getDefualtAddressId($customer_id = '') $customer_id = $identity['id']; } if (!$customer_id) { + return null; } $addressOne = $this->_addressModel->find()->asArray() ->where(['customer_id' => $customer_id,'is_default' => 1]) ->one(); if($addressOne['address_id']){ + return $addressOne['address_id']; } return null; } - /* - * @param $customer_id | int 用户的id - * @return Array Or '' - * 得到customer的默认地址。 - */ - /* - protected function actionGetDefaultAddress($customer_id = ''){ - if(!$customer_id){ - $identity = Yii::$app->user->identity; - $customer_id = $identity['id']; - } - if($customer_id ){ - $addressOne = $this->_addressModel->find()->asArray() - ->where(['customer_id' => $customer_id,'is_default' => 1]) - ->one(); - if($addressOne['address_id']){ - return $addressOne; - }else{ - $assOne = $this->_addressModel->find()->asArray() - ->where(['customer_id' => $customer_id]) - ->one(); - if($assOne['address_id']){ - return $assOne; - } - } - } - } - */ /** * 得到登陆用户的默认货运地址。 */ diff --git a/services/customer/Facebook.php b/services/customer/Facebook.php index d07f041c9..bbb13ec34 100644 --- a/services/customer/Facebook.php +++ b/services/customer/Facebook.php @@ -40,6 +40,7 @@ public function getLoginUrl($url, $customDomain = false) $this->facebook_app_id = isset($thirdLogin['facebook']['facebook_app_id']) ? $thirdLogin['facebook']['facebook_app_id'] : ''; $this->facebook_app_secret = isset($thirdLogin['facebook']['facebook_app_secret']) ? $thirdLogin['facebook']['facebook_app_secret'] : ''; if (!$this->facebook_app_id || !$this->facebook_app_secret) { + return ''; } $fb = new \Facebook\Facebook([ @@ -50,6 +51,7 @@ public function getLoginUrl($url, $customDomain = false) $helper = $fb->getRedirectLoginHelper(); $permissions = ['email']; // Optional permissions $loginUrl = $helper->getLoginUrl($redirectUrl, $permissions); + return $loginUrl; } } diff --git a/services/customer/Google.php b/services/customer/Google.php index 98d6f9112..af2dfabf4 100644 --- a/services/customer/Google.php +++ b/services/customer/Google.php @@ -42,13 +42,12 @@ public function getLoginUrl($url, $customDomain = false) $googleapiinfo['GOOGLE_CLIENT_SECRET'] = isset($thirdLogin['google']['CLIENT_SECRET']) ? $thirdLogin['google']['CLIENT_SECRET'] : ''; //echo $lib_google_base.'/Social.php';exit; if (!$googleapiinfo['GOOGLE_CLIENT_ID'] || !$googleapiinfo['GOOGLE_CLIENT_SECRET'] ) { + return ''; } $lib_google_base = Yii::getAlias('@fecshop/lib/google'); include $lib_google_base.'/Social.php'; - $Social_obj = new \Social($redirectUrl, 1); - $url = $Social_obj->google(); return $url; diff --git a/services/customer/Newsletter.php b/services/customer/Newsletter.php index d98aeadd8..9ad2942b7 100644 --- a/services/customer/Newsletter.php +++ b/services/customer/Newsletter.php @@ -74,7 +74,6 @@ public function getByPrimaryKey($primaryKey) return $this->_newsletter->getByPrimaryKey($primaryKey); } - /* * example filter: * [ diff --git a/services/customer/newsletter/NewsletterMongodb.php b/services/customer/newsletter/NewsletterMongodb.php index e3d3f7315..98681ddcb 100644 --- a/services/customer/newsletter/NewsletterMongodb.php +++ b/services/customer/newsletter/NewsletterMongodb.php @@ -41,8 +41,10 @@ public function getPrimaryKey() public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_newsletterModel->findOne($primaryKey); } else { + return new $this->_newsletterModelName(); } } @@ -82,6 +84,7 @@ protected function emailIsExist($emailAddress) $primaryKey = $this->_newsletterModel->primaryKey(); $one = $this->_newsletterModel->findOne(['email' => $emailAddress]); if ($one[$primaryKey]) { + return true; } @@ -93,7 +96,7 @@ protected function emailIsExist($emailAddress) * @return bool * 订阅邮件 */ - protected function actionSubscribe($emailAddress, $isRegister = false) + public function subscribe($emailAddress, $isRegister = false) { if (!$emailAddress) { Yii::$service->helper->errors->add('newsletter email address is empty'); @@ -105,6 +108,7 @@ protected function actionSubscribe($emailAddress, $isRegister = false) return; } elseif ($this->emailIsExist($emailAddress)) { if ($isRegister) { + return true; } else { Yii::$service->helper->errors->add('ERROR,Your email address has subscribe , Please do not repeat the subscription'); diff --git a/services/customer/newsletter/NewsletterMysqldb.php b/services/customer/newsletter/NewsletterMysqldb.php index 4b2512e34..1d0647df0 100644 --- a/services/customer/newsletter/NewsletterMysqldb.php +++ b/services/customer/newsletter/NewsletterMysqldb.php @@ -41,8 +41,10 @@ public function getPrimaryKey() public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_newsletterModel->findOne($primaryKey); } else { + return new $this->_newsletterModelName(); } } @@ -83,6 +85,7 @@ protected function emailIsExist($emailAddress) $one = $this->_newsletterModel->findOne(['email' => $emailAddress]); if ($one[$primaryKey]) { + return true; } @@ -106,6 +109,7 @@ protected function actionSubscribe($emailAddress, $isRegister = false) return; } elseif ($this->emailIsExist($emailAddress)) { if ($isRegister) { + return true; } else { Yii::$service->helper->errors->add('ERROR,Your email address has subscribe , Please do not repeat the subscription'); diff --git a/services/email/Customer.php b/services/email/Customer.php index cb7235e5c..b078be886 100644 --- a/services/email/Customer.php +++ b/services/email/Customer.php @@ -180,6 +180,7 @@ public function getPasswordResetTokenExpire() { $forgotPasswordInfo = $this->emailTheme['forgotPassword']; if (isset($forgotPasswordInfo['passwordResetTokenExpire']) && $forgotPasswordInfo['passwordResetTokenExpire']) { + return $forgotPasswordInfo['passwordResetTokenExpire']; } } diff --git a/services/email/widgets/customer/account/login/Body.php b/services/email/widgets/customer/account/login/Body.php index 03ce9fc63..ba0521eb1 100644 --- a/services/email/widgets/customer/account/login/Body.php +++ b/services/email/widgets/customer/account/login/Body.php @@ -22,6 +22,7 @@ class Body extends BodyBase public function getLastData() { $identity = Yii::$app->user->identity; + return [ 'name' => $identity['firstname'].' '. $identity['lastname'], 'email' => $identity['email'], diff --git a/services/extension/Administer.php b/services/extension/Administer.php index 2507fd3a7..16f2301af 100644 --- a/services/extension/Administer.php +++ b/services/extension/Administer.php @@ -76,10 +76,12 @@ public function install($extension_namespace, $forceInstall=false) return false; } $innerTransaction->commit(); + return true; } catch (\Exception $e) { $innerTransaction->rollBack(); Yii::$service->helper->errors->add($e->getMessage()); + return false; } @@ -124,10 +126,12 @@ public function testInstall($extension_namespace, $forceInstall=false) } $innerTransaction->commit(); + return true; } catch (\Exception $e) { $innerTransaction->rollBack(); Yii::$service->helper->errors->add($e->getMessage()); + return false; } @@ -186,6 +190,7 @@ public function upgrade($extension_namespace) } catch (\Exception $e) { $innerTransaction->rollBack(); Yii::$service->helper->errors->add($e->getMessage()); + return false; } @@ -225,6 +230,7 @@ public function testUpgrade($extension_namespace) // 执行应用的upgrade部分功能 if (!Yii::$service->extension->testUpgradeAddons($extensionConfig['administer']['upgrade'], $modelOne)) { $innerTransaction->rollBack(); + return false; } $innerTransaction->commit(); @@ -233,6 +239,7 @@ public function testUpgrade($extension_namespace) } catch (\Exception $e) { $innerTransaction->rollBack(); Yii::$service->helper->errors->add($e->getMessage()); + return false; } diff --git a/services/extension/Generate.php b/services/extension/Generate.php index 1326fa875..e5b9e51e6 100644 --- a/services/extension/Generate.php +++ b/services/extension/Generate.php @@ -88,8 +88,6 @@ public function createAddonsFiles($param) return false; } - - return true; } @@ -104,26 +102,31 @@ public function createFolder($param) $addonPath = Yii::getAlias('@addons/'.$package.'/'.$addon_folder); // 创建文件夹 if (!$this->createDir($addonPath)) { + return false; } // administer $administerPath = $addonPath . '/administer'; if (!$this->createDir($administerPath)) { + return false; } // app/appfront $appfrontPath = $addonPath . '/app/appfront'; if (!$this->createDir($appfrontPath)) { + return false; } // models $modelPath = $addonPath . '/models'; if (!$this->createDir($modelPath)) { + return false; } // services $servicesPath = $addonPath . '/services'; if (!$this->createDir($servicesPath)) { + return false; } @@ -137,6 +140,7 @@ public function createDir($dir) return false; } + return mkdir($dir,0777,true); } diff --git a/services/extension/RemoteService.php b/services/extension/RemoteService.php index 218c288f8..afa1c609a 100644 --- a/services/extension/RemoteService.php +++ b/services/extension/RemoteService.php @@ -51,6 +51,7 @@ public function getDeveloperInfo() { $accessToken = $this->getAccessToken(); if (!$accessToken) { + return false; } $url = $this->remoteUrl . $this->getDeveloperInfoUrlKey ; @@ -65,8 +66,6 @@ public function getDeveloperInfo() } return false; - - } // 得到远程的addon 信息(我的应用列表) @@ -74,6 +73,7 @@ public function getMyAddonsInfo($pageNum, $numPerPage) { $accessToken = $this->getAccessToken(); if (!$accessToken) { + return false; } $url = $this->remoteUrl . $this->getAddonsListUrlKey ; @@ -85,7 +85,6 @@ public function getMyAddonsInfo($pageNum, $numPerPage) 'numPerPage' => $numPerPage, ]; list($responseHeader, $result) = $this->getCurlData($url, 'post', $headerRequest, $data, 30); - if ($result['code'] == 200) { return $result['data']; @@ -98,6 +97,7 @@ public function getAddonsInfoByNamespace($namespace) { $accessToken = $this->getAccessToken(); if (!$accessToken) { + return false; } $url = $this->remoteUrl . $this->getAddonInfoUrlKey ; @@ -108,15 +108,12 @@ public function getAddonsInfoByNamespace($namespace) 'namespace' => $namespace, ]; list($responseHeader, $result) = $this->getCurlData($url, 'post', $headerRequest, $data, 30); - if ($result['code'] == 200) { return $result['data']; } return false; - - } // 应用zip文件报错的文件路径 public function getExtensionZipFilePath($packageName, $folderName) @@ -143,23 +140,24 @@ public function downloadAddons($namespace, $packageName, $folderName, $addonName mkdir($packagePath); chmod($packagePath, 0777); } - $filePath = $this->getExtensionZipFilePath($packageName, $folderName); // 根据文件路径,以及addon的name,得到zip文件存放的文件完整路径 //$filePath = Yii::getAlias('@addons/'.$packageName.'/'.$folderName.'/'.$folderName.'.zip'); // 将url中的zip文件,存储到该文件目录。 if ($this->downCurl($url,$filePath)) { + return $filePath; } return null; } - // 远程下载zip包 + // 远程下载zip包 function downCurl($url, $filePath) { $accessToken = $this->getAccessToken(); if (!$accessToken) { + return false; } $headerRequest = [ @@ -170,9 +168,7 @@ function downCurl($url, $filePath) curl_setopt($ch, CURLOPT_HTTPHEADER, $headerRequest - ); - - //echo $filePath;exit; + ); //设置抓取的url curl_setopt($ch, CURLOPT_URL, $url); //打开文件描述符 @@ -181,7 +177,6 @@ function downCurl($url, $filePath) //这个选项是意思是跳转,如果你访问的页面跳转到另一个页面,也会模拟访问。 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch,CURLOPT_TIMEOUT, 5000); - //执行命令 curl_exec($ch); //关闭URL请求 @@ -192,20 +187,10 @@ function downCurl($url, $filePath) return true; } - /* - public function downFile($url,$path){ - $arr=parse_url($url); - $fileName=basename($arr['path']); - $file=file_get_contents($url); - file_put_contents($path.$fileName,$file); - } - */ - public function isLogin($checkRemote = false) { if ($checkRemote) { // 进行远程检查 - } if ($this->getAccessToken()) { @@ -214,6 +199,7 @@ public function isLogin($checkRemote = false) return false; } + public function setAccessToken($access_token) { if (!$access_token) { @@ -221,30 +207,28 @@ public function setAccessToken($access_token) } return Yii::$app->session->set(self::ADDONS_TOKEN, $access_token); } + public function getAccessToken() { return Yii::$app->session->get(self::ADDONS_TOKEN); } - public static function getCurlData($url,$type="get", $headerData, $data=array(),$timeout = 30){ //对空格进行转义 $url = str_replace(' ','+',$url); - if($type == "get"){ - if(!empty($data) && is_array($data)){ - + if ($type == "get") { + if (!empty($data) && is_array($data)) { $arr = []; - foreach($data as $k=>$v){ + foreach ($data as $k=>$v) { $arr[] = $k."=".$v; } $str = implode("&",$arr); - if(strstr($url,"?")){ + if (strstr($url,"?")) { $url .= "&".$str; - }else{ + } else { $url .= "?".$str; } } - } $data = json_encode($data); $headerRequest = [ @@ -253,7 +237,6 @@ public static function getCurlData($url,$type="get", $headerData, $data=array(), 'Content-Length: ' . strlen($data) ]; $headerRequest = array_merge($headerRequest, $headerData); - $url = urldecode($url); //echo $url ;exit; $ch = curl_init(); @@ -263,14 +246,13 @@ public static function getCurlData($url,$type="get", $headerData, $data=array(), //curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch,CURLOPT_TIMEOUT,$timeout); //定义超时3秒钟 - if($type == "post"){ + if ($type == "post") { // POST数据 curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $headerRequest ); - // 把post的变量加上 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } @@ -283,11 +265,13 @@ public static function getCurlData($url,$type="get", $headerData, $data=array(), foreach ($headArr as $loop) { $arr = explode(': ', $loop); $responseHeaderArr[$arr[0]] = $arr[1]; - } // + } $reponseBody = json_decode($body, true); + return [$responseHeaderArr, $reponseBody]; } - return ['', '']; + return ['', '']; } + } diff --git a/services/extension/UninstallInterface.php b/services/extension/UninstallInterface.php index 28da7246a..0cb5bea72 100644 --- a/services/extension/UninstallInterface.php +++ b/services/extension/UninstallInterface.php @@ -18,4 +18,5 @@ interface UninstallInterface { public function run(); + } diff --git a/services/extension/UpgradeInterface.php b/services/extension/UpgradeInterface.php index 242551e53..2e4565596 100644 --- a/services/extension/UpgradeInterface.php +++ b/services/extension/UpgradeInterface.php @@ -18,4 +18,5 @@ interface UpgradeInterface { public function run($version); + } diff --git a/services/helper/AR.php b/services/helper/AR.php index 7827f460a..b29a05d87 100644 --- a/services/helper/AR.php +++ b/services/helper/AR.php @@ -106,6 +106,7 @@ public function save($model, $one, $serialize = false) } } if ($model->save()) { + return $model; } else { Yii::$service->helper->errors->add('model save fail'); diff --git a/services/helper/Appapi.php b/services/helper/Appapi.php index c57ad8350..d28a041f6 100644 --- a/services/helper/Appapi.php +++ b/services/helper/Appapi.php @@ -69,6 +69,7 @@ public function getResponseData($code, $data, $message = '') $message = $this->getMessageByCode($code); } if ($message) { + return [ 'code' => $code, 'message' => $message, @@ -77,6 +78,7 @@ public function getResponseData($code, $data, $message = '') } else { // 如果不存在,则说明系统内部调用不存在的code,报错。 $code = $this->status_invalid_code; $message = $this->getMessageByCode($code); + return [ 'code' => $code, 'message' => $message, @@ -92,6 +94,7 @@ public function getResponseData($code, $data, $message = '') public function getMessageByCode($code) { $messageArr = $this->getMessageArr(); + return isset($messageArr[$code]['message']) ? $messageArr[$code]['message'] : ''; } @@ -150,16 +153,14 @@ public function getMessageArr() $this->status_attack => [ 'message' => 'access exception, the visit to determine the attack behavior', ], - /** * 用户部分的状态码 */ $this->account_no_login_or_login_token_timeout => [ 'message' => 'account not login or token timeout', ], - - ]; + return $arr; } } diff --git a/services/helper/Appserver.php b/services/helper/Appserver.php index 0ae0c6ec5..6dd781433 100644 --- a/services/helper/Appserver.php +++ b/services/helper/Appserver.php @@ -215,12 +215,13 @@ public function getCors(){ } $corsFilterArr['Access-Control-Allow-Credentials'] = true; } - return $corsFilterArr; + return $corsFilterArr; } public function getCorsAllowHeaders() { $fecshop_uuid = Yii::$service->session->fecshop_uuid; + return ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', $fecshop_uuid, 'fecshop-lang', 'fecshop-currency', 'access-token']; } /** @@ -235,12 +236,10 @@ public function getYiiAuthCors(){ if (isset($cors['Origin']) && $cors['Origin']) { $corsFilterArr[] = 'Access-Control-Allow-Origin: ' . implode(', ', $cors['Origin']); } - if (isset($cors['Access-Control-Allow-Headers']) && is_array($cors['Access-Control-Allow-Headers'])) { $cors_allow_headers = array_merge($cors_allow_headers, $cors['Access-Control-Allow-Headers']); } $corsFilterArr[] = 'Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, ' . implode(', ', $cors_allow_headers); - if (isset($cors['Access-Control-Allow-Methods']) && is_array($cors['Access-Control-Allow-Methods'])) { $corsFilterArr[] = 'Access-Control-Allow-Methods: ' . implode(', ',$cors['Access-Control-Allow-Methods']); } @@ -261,6 +260,7 @@ public function getResponseData($code, $data, $message = '') $message = $this->getMessageByCode($code); } if ($message) { + return [ 'code' => $code, 'message' => $message, @@ -270,6 +270,7 @@ public function getResponseData($code, $data, $message = '') // 如果不存在,则说明系统内部调用不存在的 code,报错。 $code = $this->status_invalid_code; $message = $this->getMessageByCode($code); + return [ 'code' => $code, 'message' => $message, @@ -286,6 +287,7 @@ public function getResponseData($code, $data, $message = '') public function getMessageByCode($code) { $messageArr = $this->getMessageArr(); + return isset($messageArr[$code]['message']) ? $messageArr[$code]['message'] : ''; } @@ -343,8 +345,7 @@ public function getMessageArr() ], $this->status_attack => [ 'message' => 'access exception, the visit to determine the attack behavior', - ], - + ], /** * 用户部分的状态码 */ @@ -357,7 +358,6 @@ public function getMessageArr() $this->account_register_invalid_data => [ 'message' => 'account register data is invalid', ], - $this->account_login_invalid_email_or_password => [ 'message' => 'account login email or password is not correct', ], @@ -373,12 +373,9 @@ public function getMessageArr() $this->account_register_fail => [ 'message' => 'account register fail', ], - $this->account_email_not_exist => [ 'message' => 'account email not exist', ], - - $this->account_forget_password_token_timeout => [ 'message' => 'account forget password token timeout', ], @@ -388,12 +385,9 @@ public function getMessageArr() $this->account_forget_password_reset_fail => [ 'message' => 'account forget password reset fail', ], - - $this->account_address_is_not_exist => [ 'message' => 'account address id is not exist', ], - $this->account_address_save_fail => [ 'message' => 'account address save fail', ], @@ -418,9 +412,6 @@ public function getMessageArr() $this->account_wx_get_customer_by_openid_fail => [ 'message' => 'you should bind wx openid with one account', ], - - - $this->no_account_openid_and_session_key => [ 'message' => 'no_account_openid_and_session_key', ], @@ -433,38 +424,30 @@ public function getMessageArr() $this->account_register_email_exit => [ 'message' => 'account_register_email_exit', ], - $this->account_address_set_default_fail => [ 'message' => 'account_address_set_default_fail', ], - $this->account_address_edit_param_invaild => [ 'message' => 'account address edit param is invalid', ], $this->account_reorder_order_id_invalid => [ 'message' => 'customer reorder order id is invalid', ], - $this->account_favorite_id_not_exist => [ 'message' => 'customer favorite id is not exit', ], - $this->account_facebook_login_error => [ 'message' => 'login F-E-C-shop with facebook account error', ], - $this->account_google_login_error => [ 'message' => 'login F-e-c-shop with google account error', ], - - /** * category */ $this->category_not_exist => [ 'message' => 'category is not exist', ], - /** * product */ @@ -474,8 +457,6 @@ public function getMessageArr() $this->product_not_active => [ 'message' => 'product is not exist or off the shelf', ], - - $this->product_id_not_exist => [ 'message' => 'product id is not exist', ], @@ -500,16 +481,12 @@ public function getMessageArr() $this->cart_product_select_fail => [ 'message' => 'cart product select fail', ], - - - /** * Order */ $this->order_generate_product_stock_out => [ 'message' => 'before generate order,check product stock out ', ], - $this->order_generate_fail => [ 'message' => 'generate order fail', ], @@ -543,7 +520,6 @@ public function getMessageArr() $this->order_not_find_increment_id_from_dbsession => [ 'message' => 'can not find order increment id from db session storage', ], - $this->order_paypal_express_payment_fail => [ 'message' => 'order pay by paypal express api, payment fail', ], @@ -556,7 +532,6 @@ public function getMessageArr() $this->order_paypal_express_get_apiAddress_fail => [ 'message' => 'order pay by paypal express api, fetch address fail', ], - $this->order_has_been_paid => [ 'message' => 'order has bean paid', ], @@ -569,16 +544,14 @@ public function getMessageArr() $this->order_wxpay_payment_fail => [ 'message' => 'order pay by wxpay payment fail', ], - - /** * cms */ $this->cms_article_not_exist => [ 'message' => 'article is not exist', ], - ]; + return $arr; } } diff --git a/services/helper/Captcha.php b/services/helper/Captcha.php index 3bad7ad81..b14b62d5b 100644 --- a/services/helper/Captcha.php +++ b/services/helper/Captcha.php @@ -144,8 +144,10 @@ public function setSessionCode() public function getCode($code) { if (!$this->case_sensitive) { + return strtolower($code); } else { + return $this->code; } } diff --git a/services/helper/Country.php b/services/helper/Country.php index 0dc7c9574..0f8dd9fc2 100644 --- a/services/helper/Country.php +++ b/services/helper/Country.php @@ -968,9 +968,7 @@ public function getCountryStateArr() 'NX' => '宁夏回族自治区', 'XJ' => '新疆维吾尔自治区', 'XG' => '香港特别行政区', - ], - ]; return $data; diff --git a/services/helper/Echart.php b/services/helper/Echart.php index da149ae9f..ab176f540 100644 --- a/services/helper/Echart.php +++ b/services/helper/Echart.php @@ -68,7 +68,6 @@ public function getLine($data, $legend = false, $yPrex = '', $width = '100%', $h { $this->i++; $div_id = "main_".$this->i; - $legendArr = []; $xAxis = []; $series = []; @@ -91,7 +90,6 @@ public function getLine($data, $legend = false, $yPrex = '', $width = '100%', $h $xAxisArr[] = '\''.$s.'\''; } $xAxisStr = implode(',', $xAxisArr); - // 计算series $seriesArr = []; if (is_array($data)) { diff --git a/services/helper/Errors.php b/services/helper/Errors.php index 0a7c0cec7..603655ace 100644 --- a/services/helper/Errors.php +++ b/services/helper/Errors.php @@ -49,7 +49,6 @@ public function addByModelErrors($model_errors) if (is_array($model_errors)) { foreach ($model_errors as $errors) { $arr = []; - foreach ($errors as $s) { $arr[] = Yii::$service->page->translate->__($s); } @@ -67,13 +66,13 @@ public function getModelErrorsStrFormat($model_errors) if (is_array($model_errors)) { foreach ($model_errors as $errors) { $arr = []; - foreach ($errors as $s) { $arr[] = Yii::$service->page->translate->__($s); } $error_arr[] = implode(',', $arr); } if (!empty($error_arr)) { + return implode(',', $error_arr); } } @@ -96,6 +95,7 @@ public function get($separator = false) return implode($separator, $errors); } else { + return $errors; } } diff --git a/services/helper/Format.php b/services/helper/Format.php index 615799eca..eefbea214 100644 --- a/services/helper/Format.php +++ b/services/helper/Format.php @@ -42,6 +42,8 @@ public function getPreDayDateArr($day) $str = date("Y-m-d", strtotime("-$i day")); $arr[$str] = 0; } + return $arr; } + } diff --git a/services/helper/Wx.php b/services/helper/Wx.php index 1c6d13ed9..5d2632ec3 100644 --- a/services/helper/Wx.php +++ b/services/helper/Wx.php @@ -34,6 +34,7 @@ public function init() parent::init(); $wxpayConfigFile = Yii::getAlias($this->configFile); if (!is_file($wxpayConfigFile)) { + throw new InvalidConfigException('wxpay config file:['.$wxpayConfigFile.'] is not exist'); } $appId = Yii::$app->store->get('payment_wxpay', 'wechat_micro_app_id' ); @@ -44,14 +45,12 @@ public function init() define('WX_APP_SECRET', $appSecret); define('WX_MCH_KEY', $mchKey); define('WX_MCH_ID', $mchId); - require_once($wxpayConfigFile); // 通过上面的小程序,设置配置信息 $this->microProgramAppId = \WxPayConfig::APPID; $this->microProgramSecret = \WxPayConfig::APPSECRET; } - /** * @param $code | string, 微信登陆的code * @return array , example: ['session_key' => '', 'openid' => ''] @@ -62,17 +61,14 @@ public function getUserInfoByCode($code) $apiId = $this->microProgramAppId; $secret = $this->microProgramSecret; $grant_type = 'authorization_code'; - $url = $this->wxApiBaseUrl . $urlKey . "?appid=$apiId&secret=$secret&js_code=$code&grant_type=$grant_type"; - //echo $url; exit; $returnStr = \fec\helpers\CApi::getCurlData($url); $wxUserInfo = json_decode($returnStr, true); if (!isset($wxUserInfo['session_key']) || !isset($wxUserInfo['openid']) ) { + return null; } - // 保存到session - //Yii::$service->helper->wx->setWxSessionKeyAndOpenid($wxUserInfo['session_key'], $wxUserInfo['openid']); - + return $wxUserInfo; } diff --git a/services/helper/ZipFile.php b/services/helper/ZipFile.php index 1dc4dc581..18f38fd12 100644 --- a/services/helper/ZipFile.php +++ b/services/helper/ZipFile.php @@ -61,10 +61,13 @@ public function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $ov zip_close($zip); } }else{ + return false; } + return true; } + /** * 创建目录 */ @@ -82,6 +85,7 @@ public function create_dirs($path){ } } } + } diff --git a/services/helper/errorhandler/ErrorHandlerInterface.php b/services/helper/errorhandler/ErrorHandlerInterface.php index d8de62463..c3ea25b9b 100644 --- a/services/helper/errorhandler/ErrorHandlerInterface.php +++ b/services/helper/errorhandler/ErrorHandlerInterface.php @@ -34,5 +34,5 @@ public function saveByErrorHandler( $req_info=[] ); - //public function remove($ids); + } diff --git a/services/helper/errorhandler/ErrorHandlerMongodb.php b/services/helper/errorhandler/ErrorHandlerMongodb.php index fdee82d8a..9243d8d9c 100644 --- a/services/helper/errorhandler/ErrorHandlerMongodb.php +++ b/services/helper/errorhandler/ErrorHandlerMongodb.php @@ -73,6 +73,7 @@ public function saveByErrorHandler( $model->request_info = $req_info; $model->trace_string = $trace_string; $model->save(); + return (string)$model[$this->getPrimaryKey()]; } @@ -82,6 +83,7 @@ public function saveByErrorHandler( public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_errorHandlerModel->findOne($primaryKey); } } @@ -110,6 +112,7 @@ public function coll($filter = '') $coll[$k] = $one; } } + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), diff --git a/services/helper/errorhandler/ErrorHandlerMysqldb.php b/services/helper/errorhandler/ErrorHandlerMysqldb.php index 92e77e622..be3e75da7 100644 --- a/services/helper/errorhandler/ErrorHandlerMysqldb.php +++ b/services/helper/errorhandler/ErrorHandlerMysqldb.php @@ -73,6 +73,7 @@ public function saveByErrorHandler( $model->request_info = serialize($req_info); $model->trace_string = $trace_string; $model->save(); + return (string)$model[$this->getPrimaryKey()]; } @@ -82,6 +83,7 @@ public function saveByErrorHandler( public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_errorHandlerModel->findOne($primaryKey); } } @@ -111,6 +113,7 @@ public function coll($filter = '') $coll[$k] = $one; } } + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), diff --git a/services/order/Item.php b/services/order/Item.php index da04eff15..c443f7e0e 100644 --- a/services/order/Item.php +++ b/services/order/Item.php @@ -34,7 +34,7 @@ public function init() /** * 得到order 表的id字段。 */ - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return 'item_id'; } @@ -44,13 +44,15 @@ protected function actionGetPrimaryKey() * @return Object($this->_itemModel) * 通过主键值,返回Order Model对象 */ - protected function actionGetByPrimaryKey($primaryKey) + public function getByPrimaryKey($primaryKey) { $one = $this->_itemModel->findOne($primaryKey); $primaryKey = $this->getPrimaryKey(); if ($one[$primaryKey]) { + return $one; } else { + return new $this->_orderModelName(); } } @@ -61,10 +63,11 @@ protected function actionGetByPrimaryKey($primaryKey) * @param $month | int, 几个月内的订单 * 通过product_id和customerId,得到$month个月内下单支付成功的产品 */ - protected function actionGetByProductIdAndCustomerId($product_id, $month, $customer_id = 0) + public function getByProductIdAndCustomerId($product_id, $month, $customer_id = 0) { if (!$customer_id) { if (Yii::$app->user->isGuest) { + return false; } else { $customer_id = Yii::$app->user->identity->id; @@ -90,6 +93,7 @@ protected function actionGetByProductIdAndCustomerId($product_id, $month, $custo } } if (empty($order_ids)) { + return false; } $items = $this->_itemModel->find()->asArray()->where([ @@ -99,8 +103,10 @@ protected function actionGetByProductIdAndCustomerId($product_id, $month, $custo ]) ->all(); if (!empty($items)) { + return $items; } else { + return false; } } @@ -111,20 +117,19 @@ protected function actionGetByProductIdAndCustomerId($product_id, $month, $custo * @return array * 通过order_id 得到所有的items */ - protected function actionGetByOrderId($order_id, $onlyFromTable = false) + public function getByOrderId($order_id, $onlyFromTable = false) { $items = $this->_itemModel->find()->asArray()->where([ 'order_id' => $order_id, ])->all(); if ($onlyFromTable) { + return $items; } foreach ($items as $k=>$one) { $product_id = $one['product_id']; $product_one = Yii::$service->product->getByPrimaryKey($product_id); - $productSpuOptions = $this->getProductSpuOptions($product_one); - //var_dump($productSpuOptions); $items[$k]['spu_options'] = $productSpuOptions; $items[$k]['custom_option'] = $product_one['custom_option']; $items[$k]['custom_option_info'] = $this->getProductOptions($items[$k]); @@ -140,12 +145,13 @@ protected function actionGetByOrderId($order_id, $onlyFromTable = false) * @return array * 通过order_id 得到所有的items */ - protected function actionGetByOrderIds($order_ids, $onlyFromTable = false) + public function getByOrderIds($order_ids, $onlyFromTable = false) { $items = $this->_itemModel->find()->asArray()->where([ 'in', 'order_id', $order_ids, ])->all(); if ($onlyFromTable) { + return $items; } foreach ($items as $k=>$one) { @@ -268,6 +274,7 @@ protected function getProductSpuOptions($productOb) } } } + return $custom_option_info_arr; } @@ -299,7 +306,7 @@ protected function getProductSpuOptions($productOb) * @param $order_id | Int * 保存订单的item信息 */ - protected function actionSaveOrderItems($items, $order_id, $store) + public function saveOrderItems($items, $order_id, $store) { /** * 由于是通过session查订单的方式,而不是新建,paypal报错可能多次下单(更新方式), @@ -341,10 +348,12 @@ protected function actionSaveOrderItems($items, $order_id, $store) $saveStatus = $myOrderItem->save(); // 如果保存失败,直接返回。 if (!$saveStatus) { + return $saveStatus; } } } + return true; } @@ -366,7 +375,7 @@ protected function actionSaveOrderItems($items, $order_id, $store) * ] * 根据$filter 搜索参数数组,返回满足条件的订单数据。 */ - protected function actionColl($filter = '') + public function coll($filter = '') { $query = $this->_itemModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); diff --git a/services/page/Asset.php b/services/page/Asset.php index 583eed23a..587e95db2 100644 --- a/services/page/Asset.php +++ b/services/page/Asset.php @@ -65,12 +65,11 @@ public function init() $css_version = Yii::$app->store->get($appName.'_base', 'css_version'); $this->jsVersion = $js_version; $this->cssVersion = $css_version; - } /** * 文件路径默认放到模板路径下面的assets里面. */ - protected function actionRegister($view) + public function register($view) { if ($this->basePath) { $view->assetManager->basePath = Yii::getAlias($this->basePath); @@ -94,6 +93,7 @@ protected function actionRegister($view) 'js' => $jsPath, 'options' => isset($jsOption['options']) ? $this->initOptions($jsOption['options']) : null, ]; + break; } } @@ -101,7 +101,6 @@ protected function actionRegister($view) } } } - if (is_array($this->cssOptions) && !empty($this->cssOptions)) { foreach ($this->cssOptions as $cssOption) { if (isset($cssOption['css']) && is_array($cssOption['css']) && !empty($cssOption['css'])) { @@ -114,6 +113,7 @@ protected function actionRegister($view) 'css' => $cssPath, 'options' => isset($cssOption['options']) ? $this->initOptions($cssOption['options']) : null, ]; + break; } } @@ -131,13 +131,11 @@ protected function actionRegister($view) $publishDir = $view->assetManager->publish($fileDir); if (!empty($jsConfig) && is_array($jsConfig)) { foreach ($jsConfig as $c) { - //$view->registerJsFile($this->jsCssDomain.$publishDir[1].'/'.$c['js'].$jsV, $c['options']); $view->registerJsFile($publishDir[1].'/'.$c['js'].$jsV, $c['options']); } } if (!empty($cssConfig) && is_array($cssConfig)) { foreach ($cssConfig as $c) { - //$view->registerCssFile($this->jsCssDomain.$publishDir[1].'/'.$c['css'].$cssV, $c['options']); $view->registerCssFile($publishDir[1].'/'.$c['css'].$cssV, $c['options']); } } diff --git a/services/page/Breadcrumbs.php b/services/page/Breadcrumbs.php index ad823a63c..6ed13fff8 100644 --- a/services/page/Breadcrumbs.php +++ b/services/page/Breadcrumbs.php @@ -48,7 +48,7 @@ public function init() * $items format example. 将各个部分的链接加入到面包屑导航中 * $items = ['name'=>'fashion handbag','url'=>'http://www.xxx.com'];. */ - protected function actionAddItems($items) + public function addItems($items) { if ($this->active) { $this->_items[] = $items; @@ -59,37 +59,17 @@ protected function actionAddItems($items) * 通过上面的方法addItems($items),把item加入进来后 * 然后,通过该函数取出来。 */ - protected function actionGetItems() + public function getItems() { if ($this->active) { if (is_array($this->_items) && !empty($this->_items)) { + return $this->_items; } else { + return []; } } } - // generate Breadcrumbs html ,before generate , you should use addItems function to add breadcrumbs items. - /* - protected function actionGenerateHtml(){ - $arr = []; - if($this->_items){ - foreach($this->_items as $item){ - $name = isset($item['name']) ? $item['name'] : ''; - $url = isset($item['url']) ? $item['url'] : ''; - if($name){ - if($url){ - $arr[] = ''.$name.''; - }else{ - $arr[] = ''.$name.''; - } - } - } - } - return $arr; - //if(!empty($arr)) - // return implode($this->intervalSymbol,$arr); - } - */ } diff --git a/services/page/Currency.php b/services/page/Currency.php index 82451a274..33d0d014c 100644 --- a/services/page/Currency.php +++ b/services/page/Currency.php @@ -68,7 +68,6 @@ public function init() // init default and base currency $this->defaultCurrency = Yii::$app->store->get('base_info', 'default_currency'); $this->baseCurrecy = Yii::$app->store->get('base_info', 'base_currency'); - // init all currency $currencys = Yii::$app->store->get('currency'); if (is_array($currencys)) { @@ -90,7 +89,7 @@ public function init() * 如果不传递参数,得到所有的货币 * 如果传递参数,得到的是当前货币的信息。 */ - protected function actionGetCurrencys($currencyCode = '') + public function getCurrencys($currencyCode = '') { if (!$this->_currencys) { foreach ($this->currencys as $code => $info) { @@ -119,9 +118,10 @@ protected function actionGetCurrencys($currencyCode = '') * 得到当前货币的符号,譬如¥ $ 等。 * 如果当前的货币在配置中找不到,则会强制改成默认货币 */ - protected function actionGetCurrentSymbol() + public function getCurrentSymbol() { if (isset($this->currencys[$this->getCurrentCurrency()]['symbol'])) { + return $this->currencys[$this->getCurrentCurrency()]['symbol']; } } @@ -130,9 +130,10 @@ protected function actionGetCurrentSymbol() * @param $currencyCode | 货币简码 * 得到货币的符号,譬如¥ $ 等。 */ - protected function actionGetSymbol($currencyCode) + public function getSymbol($currencyCode) { if (isset($this->currencys[$currencyCode]['symbol'])) { + return $this->currencys[$currencyCode]['symbol']; } } @@ -142,6 +143,7 @@ protected function actionGetSymbol($currencyCode) public function getBaseSymbol() { if (isset($this->currencys[$this->baseCurrecy]['symbol'])) { + return $this->currencys[$this->baseCurrecy]['symbol']; } } @@ -152,11 +154,12 @@ public function getBaseSymbol() * current currency will set defaultCurrency, origin price will be return. * 通过传递默认货币的价格,得到当前货币的价格。 */ - protected function actionGetCurrentCurrencyPrice($price) + public function getCurrentCurrencyPrice($price) { $currencyCode = $this->getCurrentCurrency(); $currencyPrice = $this->getCurrencyPrice($price, $currencyCode); if ($currencyPrice !== null) { + return $currencyPrice; } /* @@ -173,11 +176,12 @@ protected function actionGetCurrentCurrencyPrice($price) * property $currencyCode|String,货币简码,譬如 USD * 根据基础货币,得到相应货币的价格 */ - protected function actionGetCurrencyPrice($price, $currencyCode) + public function getCurrencyPrice($price, $currencyCode) { if (isset($this->currencys[$currencyCode]['rate'])) { $rate = $this->currencys[$currencyCode]['rate']; if ($rate) { + return bcmul($price, $rate, 2); } } @@ -192,7 +196,7 @@ protected function actionGetCurrencyPrice($price, $currencyCode) * 需要特别注意的是:这种反推方法换算得到的基础货币的价格,和原来的基础货币价格, * 可能有0.01的误差,因为默认货币换算成当前货币的算法为小数点后两位进一法得到的。 */ - protected function actionGetBaseCurrencyPrice($current_price, $current_currency = '') + public function getBaseCurrencyPrice($current_price, $current_currency = '') { if (!$current_currency) { $current_currency = $this->getCurrentCurrency(); @@ -200,6 +204,7 @@ protected function actionGetBaseCurrencyPrice($current_price, $current_currency if (isset($this->currencys[$current_currency]['rate'])) { $rate = $this->currencys[$current_currency]['rate']; if ($rate) { + return bcdiv($current_price, $rate, 2); } } @@ -211,12 +216,14 @@ protected function actionGetBaseCurrencyPrice($current_price, $current_currency * 1. 如果 $this->defaultCurrency 和 $this->baseCurrecy 没有设置,将会报错。 * 2. 如果 传递参数$currencyCode为空,则会使用默认货币 */ - protected function actionInitCurrency($currencyCode = '') + public function initCurrency($currencyCode = '') { if (!$this->defaultCurrency) { + throw new InvalidConfigException('defautlt currency must config'); } if (!$this->baseCurrecy) { + throw new InvalidConfigException('base currency must config'); } if (!$this->getCurrentCurrency()) { @@ -237,7 +244,7 @@ protected function actionInitCurrency($currencyCode = '') * 'symbol' => $symbol , * ] */ - protected function actionGetCurrencyInfo($currencyCode = '') + public function getCurrencyInfo($currencyCode = '') { if (!$currencyCode) { $currencyCode = $this->getCurrentCurrency(); @@ -249,7 +256,7 @@ protected function actionGetCurrencyInfo($currencyCode = '') /** * 得到当前的货币。 */ - protected function actionGetCurrentCurrency() + public function getCurrentCurrency() { if (!$this->_currentCurrencyCode) { $this->_currentCurrencyCode = Yii::$service->session->get(self::CURRENCY_CURRENT); @@ -262,7 +269,7 @@ protected function actionGetCurrentCurrency() * @param $currencyCode | String, 当前的货币简码 * 设置当前的货币。 */ - protected function actionSetCurrentCurrency($currencyCode) + public function setCurrentCurrency($currencyCode) { if (!$this->isCorrectCurrency($currencyCode)) { $currencyCode = $this->defaultCurrency; @@ -272,6 +279,7 @@ protected function actionSetCurrentCurrency($currencyCode) Yii::$service->session->set(self::CURRENCY_CURRENT, $currencyCode); } $this->_currentCurrencyCode = $currencyCode; + return true; } } @@ -285,6 +293,7 @@ protected function actionSetCurrentCurrency($currencyCode) public function appserverSetCurrentCurrency() { if ($this->_currentCurrencyCode) { + return true; } $header = Yii::$app->request->getHeaders(); @@ -309,8 +318,10 @@ public function appserverSetCurrentCurrency() protected function isCorrectCurrency($currencyCode) { if (isset($this->currencys[$currencyCode])) { + return true; } else { + return false; } } diff --git a/services/page/Menu.php b/services/page/Menu.php index dc92b72e0..e0aa8fabc 100644 --- a/services/page/Menu.php +++ b/services/page/Menu.php @@ -43,7 +43,7 @@ class Menu extends Service * home,frontCustomMenu,productCategory,behindCustomMenu. * 得到网站的分类导航栏菜单。 */ - protected function actionGetMenuData() + public function getMenuData() { $this->_homeUrl = CUrl::getHomeUrl(); $arr = []; diff --git a/services/page/Message.php b/services/page/Message.php index 126b006ba..1a7403653 100644 --- a/services/page/Message.php +++ b/services/page/Message.php @@ -28,9 +28,10 @@ class Message extends Service * @param $message | String * 增加 correct message. 添加一些操作成功的提示信息,譬如产品加入购物车成功 */ - protected function actionAddCorrect($message) + public function addCorrect($message) { if (empty($message)) { + return; } if (is_string($message)) { @@ -48,9 +49,10 @@ protected function actionAddCorrect($message) * @param $message | String * 增加 error message. */ - protected function actionAddError($message) + public function addError($message) { if (empty($message)) { + return; } if (is_string($message)) { @@ -74,7 +76,7 @@ protected function actionAddError($message) * Yii::$service->page->message是要在前台页面显示的。 * 而 Yii::$service->helper->errors 不会在前台显示,只是记录Yii Service执行过程中的报错信息。 */ - protected function actionAddByHelperErrors() + public function addByHelperErrors() { $errors = Yii::$service->helper->errors->get(); //var_dump($errors); @@ -93,12 +95,14 @@ protected function actionAddByHelperErrors() * 获取 correct message. * @return array */ - protected function actionGetCorrects() + public function getCorrects() { $corrects = Yii::$service->session->getFlash($this->_correctName); if ($corrects && !is_array($corrects)) { + return [$corrects]; } else { + return $corrects; } } @@ -107,12 +111,14 @@ protected function actionGetCorrects() * 获取 error message. * @return array */ - protected function actionGetErrors() + public function getErrors() { $errors = Yii::$service->session->getFlash($this->_errorName); if ($errors && !is_array($errors)) { + return [$errors]; } else { + return $errors; } } diff --git a/services/page/Newsletter.php b/services/page/Newsletter.php index 61945261e..ec46df1f0 100644 --- a/services/page/Newsletter.php +++ b/services/page/Newsletter.php @@ -72,7 +72,4 @@ public function getSubscriptionList($filter) } - - - } diff --git a/services/page/Theme.php b/services/page/Theme.php index af069f640..0b133f0e1 100644 --- a/services/page/Theme.php +++ b/services/page/Theme.php @@ -54,14 +54,13 @@ class Theme extends Service * @return array ,根据模板路径的优先级,以及得到各个模板路径,组合成数组 * 数组前面的模板路径优先级最高 */ - protected function actionGetThemeDirArr() + public function getThemeDirArr() { if (!$this->_themeDirArr || empty($this->_themeDirArr)) { $arr = []; if ($localThemeDir = Yii::getAlias($this->localThemeDir)) { $arr[] = $localThemeDir; } - $thirdThemeDirArr = $this->thirdThemeDir; if (!empty($thirdThemeDirArr) && is_array($thirdThemeDirArr)) { foreach ($thirdThemeDirArr as $theme) { @@ -80,10 +79,11 @@ protected function actionGetThemeDirArr() * @param $throwError | boolean,view文件找不到的时候是否抛出异常。 * 根据模板路径的优先级,依次查找view文件,找到后,返回view文件的绝对路径。 */ - protected function actionGetViewFile($view, $throwError = true) + public function getViewFile($view, $throwError = true) { $view = trim($view); if (substr($view, 0, 1) == '@') { + return Yii::getAlias($view); } $relativeFile = ''; @@ -97,18 +97,18 @@ protected function actionGetViewFile($view, $throwError = true) $relativeFile = $this->viewFileConfig[$routerPath]; // 如果view是以@开头,则说明是绝对路径,直接返回 if (substr($relativeFile, 0, 1) == '@') { + return Yii::getAlias($relativeFile); } } else { $relativeFile .= Yii::$app->controller->id.'/'.$view.'.php'; } - - $absoluteDir = Yii::$service->page->theme->getThemeDirArr(); foreach ($absoluteDir as $dir) { if ($dir) { $file = $dir.'/'.$relativeFile; if (file_exists($file)) { + return $file; } } @@ -122,8 +122,10 @@ protected function actionGetViewFile($view, $throwError = true) $notExistFile[] = $file; } } + throw new InvalidValueException('view file is not exist in'.implode(',', $notExistFile)); } else { + return false; } } @@ -131,7 +133,7 @@ protected function actionGetViewFile($view, $throwError = true) /** * @param $dir | string 设置本地模板路径 */ - protected function actionSetLocalThemeDir($dir) + public function setLocalThemeDir($dir) { $this->localThemeDir = $dir; } @@ -139,7 +141,7 @@ protected function actionSetLocalThemeDir($dir) /** * @param $dir | string 设置第三方模板路径 */ - protected function actionSetThirdThemeDir($dir) + public function setThirdThemeDir($dir) { $this->thirdThemeDir = $dir; } diff --git a/services/page/Trace.php b/services/page/Trace.php index d49f9eb9a..ddaac1548 100644 --- a/services/page/Trace.php +++ b/services/page/Trace.php @@ -78,6 +78,7 @@ class Trace extends Service public function getTraceCommonJsCode() { if ($this->traceJsEnable) { + return ""; } else { + return ''; } } @@ -105,11 +107,13 @@ public function getTraceCommonJsCode() public function getTraceCategoryJsCode($categoryName) { if ($this->traceJsEnable && $categoryName) { + return ""; } else { + return ''; } } diff --git a/services/page/Translate.php b/services/page/Translate.php index fded2f0ac..f8d482f31 100644 --- a/services/page/Translate.php +++ b/services/page/Translate.php @@ -58,7 +58,7 @@ public function __($text, $arr = []) * * @param string $language the language to be set. */ - protected function actionSetLanguage($language) + public function setLanguage($language) { Yii::$app->language = $language; } diff --git a/services/page/Widget.php b/services/page/Widget.php index 527ebef1d..998f5ebb9 100644 --- a/services/page/Widget.php +++ b/services/page/Widget.php @@ -27,7 +27,13 @@ class Widget extends Service public $defaultObMethod = 'getLastData'; public $widgetConfig; - + + public $_cache_arr = [ + 'head' => 'headBlockCache', + 'header' => 'headerBlockCache', + 'menu' => 'menuBlockCache', + 'footer' => 'footerBlockCache', + ]; /** * @param configKey String or Array * 如果传递的是一个配置数组,内容格式如下: @@ -52,7 +58,7 @@ class Widget extends Service * 由block提供,最终生成一个html区块,返回。 * @param $parentThis 外部传递的数组变量,作为变量,可以在view中直接使用 */ - protected function actionRender($configKey, $parentThis = '') + public function render($configKey, $parentThis = '') { $config = ''; if (is_array($configKey)) { @@ -60,13 +66,14 @@ protected function actionRender($configKey, $parentThis = '') $configKey = ''; } else if ($configKey){ $configArr = explode('/', $configKey); - if (count($configArr) < 2 ) { + throw new InvalidValueException(" config key: '$configKey', format: `xxxx/xxxx`, you must config it with correct format"); } if (isset($this->widgetConfig[$configArr[0]][$configArr[1]])) { $config = $this->widgetConfig[$configArr[0]][$configArr[1]]; } else { + throw new InvalidValueException(" config key: '$configKey', can not find in ".'Yii::$service->page->widget->widgetConfig'.', you must config it before use it.'); } } @@ -97,30 +104,31 @@ protected function actionRender($configKey, $parentThis = '') * 由block提供,最终生成一个html区块,返回。 * @param $diConfig | array 数组变量,会注入$configKey中class对应的类变量 */ - protected function actionDiRender($configKey, $diConfig = []) + public function diRender($configKey, $diConfig = []) { if (!is_array($diConfig)) { + throw new InvalidValueException(" configParent: '$diConfig' must be array"); } - // - $config = ''; if (is_array($configKey)) { $config = $configKey; $configKey = ''; } else if ($configKey){ $configArr = explode('/', $configKey); - if (count($configArr) < 2 ) { + throw new InvalidValueException(" config key: '$configKey', format: `xxxx/xxxx`, you must config it with correct format"); } if (isset($this->widgetConfig[$configArr[0]][$configArr[1]])) { $config = $this->widgetConfig[$configArr[0]][$configArr[1]]; } else { + throw new InvalidValueException(" config key: '$configKey', can not find in ".'Yii::$service->page->widget->widgetConfig'.', you must config it before use it.'); } } if (!isset($config['class']) || !$config['class']) { + throw new InvalidConfigException('in widget ['.$configKey.'],you enable cache ,you must config widget class .'); } foreach ($diConfig as $k=>$v) { @@ -136,10 +144,11 @@ protected function actionDiRender($configKey, $diConfig = []) * @param $parentThis | array or '' , 调用层传递的参数数组,可以在view中调用。 * */ - protected function actionRenderContentHtml($configKey, $config, $parentThis = '') + public function renderContentHtml($configKey, $config, $parentThis = '') { if (!isset($config['view']) || empty($config['view']) ) { + throw new InvalidConfigException('view and class must exist in array config!'); } $params = []; @@ -168,20 +177,13 @@ protected function actionRenderContentHtml($configKey, $config, $parentThis = '' return Yii::$app->view->renderFile($viewFile, $params); } - public $_cache_arr = [ - 'head' => 'headBlockCache', - 'header' => 'headerBlockCache', - 'menu' => 'menuBlockCache', - 'footer' => 'footerBlockCache', - ]; - /** * @param $configKey | string , 标记,以及报错排查时使用的key。 * @param $config,就是上面actionRender()方法中的参数,格式一样。 * @param $parentThis | array or '' , 调用层传递的参数数组,可以在view中调用。 * */ - protected function actionRenderContent($configKey, $config, $parentThis = '') + public function renderContent($configKey, $config, $parentThis = '') { // 从配置中读取cache的enable状态 $cacheEnable = false; @@ -207,6 +209,7 @@ protected function actionRenderContent($configKey, $config, $parentThis = '') return $content; } else { + throw new InvalidConfigException($config['class'].' must implete fecshop\interfaces\block\BlockCache when you use block cache .'); } } @@ -225,20 +228,18 @@ protected function getViewFile($view, $throwError = true) { $view = trim($view); if (substr($view, 0, 1) == '@') { + return Yii::getAlias($view); } $absoluteDir = Yii::$service->page->theme->getThemeDirArr(); - foreach ($absoluteDir as $dir) { if ($dir) { $file = $dir.'/'.$view; - //echo $file."
"; if (file_exists($file)) { return $file; } } } - // not find view file if ($throwError) { $notExistFile = []; @@ -248,9 +249,12 @@ protected function getViewFile($view, $throwError = true) $notExistFile[] = $file; } } + throw new InvalidValueException('view file is not exist in'.implode(',', $notExistFile)); } else { + return false; } } + } diff --git a/services/payment/Alipay.php b/services/payment/Alipay.php index b947c897b..8fb62d134 100644 --- a/services/payment/Alipay.php +++ b/services/payment/Alipay.php @@ -76,7 +76,6 @@ class Alipay extends Service protected $_initAlipayLib = 0; - /** * 支付宝:SDK工作目录 * 存放日志,AOP缓存数据 @@ -116,8 +115,6 @@ public function init() } } - - /** * 初始化 $this->_AopClient */ @@ -173,8 +170,6 @@ protected function validateReviewOrder($out_trade_no, $total_amount, $seller_id, return false; } - //$base_grand_total = $this->_order['base_grand_total']; - //$order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total,'CNY'); $order_total_amount = $this->_order['grand_total']; if ($order_total_amount != $total_amount) { Yii::$service->helper->errors->add('order increment id:{out_trade_no} , total_amount({total_amount}) is not equal to order_total_amount({order_total_amount})', ['out_trade_no'=>$out_trade_no , 'total_amount'=>$total_amount , 'order_total_amount'=>$order_total_amount ]); @@ -204,7 +199,7 @@ protected function validateReviewOrder($out_trade_no, $total_amount, $seller_id, * 支付宝 支付成功后,返回网站,调用该函数进行支付宝订单支付状态查询 * 如果支付成功,则修改订单状态为支付成功状态。 */ - protected function actionReview() + public function review() { $this->initParam(); $trade_no = Yii::$app->request->get('trade_no'); @@ -214,6 +209,7 @@ protected function actionReview() $auth_app_id = Yii::$app->request->get('auth_app_id'); //验证订单的合法性 if (!$this->validateReviewOrder($out_trade_no, $total_amount, $seller_id, $auth_app_id)) { + return false; } $this->_AopClient->postCharset = $this->charset; @@ -267,7 +263,6 @@ public function receiveIpn() Yii::info('alipay service receiveIpn(): [ seller_id: ]'.$seller_id, 'fecshop_debug'); Yii::info('alipay service receiveIpn(): [ auth_app_id: ]'.$auth_app_id, 'fecshop_debug'); Yii::info('alipay service receiveIpn(): [ trade_status: ]'.$trade_status, 'fecshop_debug'); - //验证订单的合法性 if (!$this->validateReviewOrder($out_trade_no, $total_amount, $seller_id, $auth_app_id)) { Yii::info('alipay service receiveIpn(): validate order fail', 'fecshop_debug'); @@ -284,6 +279,7 @@ public function receiveIpn() } } } else { + return false; } } @@ -316,31 +312,7 @@ protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } - // 【优化后的代码 ##】 - /* 注释掉的原来代码,上面进行了优化,保证更改只有一次,这样发邮件也就只有一次了 - // 如果订单状态已经是processing,那么,不需要更改订单状态了。 - if ($this->_order['order_status'] == Yii::$service->order->payment_status_confirmed){ - - return true; - } - $order = $this->_order; - if (isset($order['increment_id']) && $order['increment_id']) { - // 如果支付成功,则更改订单状态为支付成功 - $order->order_status = Yii::$service->order->payment_status_confirmed; - $order->txn_id = $trade_no; // 支付宝的交易号 - // 更新订单信息 - $order->save(); - Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']); - // 上面的函数已经执行下面的代码,因此注释掉。 - // 得到当前的订单信息 - //$orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order['increment_id']); - // 发送新订单邮件 - //Yii::$service->email->order->sendCreateEmail($orderInfo); - - return true; - } - */ return true; } @@ -361,9 +333,9 @@ public function start($returnUrl = '', $type="POST") $this->_alipayRequest = new \AlipayTradePagePayRequest(); } else { Yii::$service->helper->errors->add('you must config param [devide] in payment alipay service'); + return; } - // 根据订单得到json格式的支付宝支付参数。 $bizContent = $this->getStartBizContentAndSetPaymentMethod(); if (!$bizContent) { @@ -375,14 +347,6 @@ public function start($returnUrl = '', $type="POST") $returnUrl = Yii::$service->payment->getStandardReturnUrl(); } $notifyUrl = Yii::$service->payment->getStandardIpnUrl(); - /* - echo $returnUrl; - echo '#'; - echo $notifyUrl; - echo '#'; - echo $bizContent; - exit; - */ $this->_alipayRequest->setReturnUrl($returnUrl); $this->_alipayRequest->setNotifyUrl($notifyUrl); $this->_alipayRequest->setBizContent($bizContent); @@ -405,10 +369,9 @@ protected function getStartBizContentAndSetPaymentMethod() if (!empty($subject_arr)) { $subject = implode(',', $subject_arr); $increment_id = $currentOrderInfo['increment_id']; - //$base_grand_total = $currentOrderInfo['base_grand_total']; - //$total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total,'CNY'); $total_amount = $currentOrderInfo['grand_total']; Yii::$service->payment->setPaymentMethod($currentOrderInfo['payment_method']); + return json_encode([ // param 参看:https://docs.open.alipay.com/common/105901 'out_trade_no' => $increment_id, diff --git a/services/payment/Paypal.php b/services/payment/Paypal.php index 2314eb9dd..81e253773 100644 --- a/services/payment/Paypal.php +++ b/services/payment/Paypal.php @@ -62,26 +62,20 @@ class Paypal extends Service public $standard_payment_method; public $version = '109.0'; - public $crt_file; - protected $_postData; - protected $_order; const EXPRESS_TOKEN = 'paypal_express_token'; - const EXPRESS_PAYER_ID = 'paypal_express_payer_id'; protected $payerID; - protected $token; // 允许更改的订单状态,不存在这里面的订单状态不允许修改 protected $_allowChangOrderStatus; protected $_ipnMessageModelName = '\fecshop\models\mysqldb\IpnMessage'; - protected $_ipnMessageModel; protected $_account; @@ -96,7 +90,6 @@ public function init() $this->_password = Yii::$app->store->get('payment_paypal', 'paypal_password'); $this->_signature = Yii::$app->store->get('payment_paypal', 'paypal_signature'); $this->_env = Yii::$app->store->get('payment_paypal', 'paypal_env'); - list($this->_ipnMessageModelName, $this->_ipnMessageModel) = \Yii::mapGet($this->_ipnMessageModelName); $this->_allowChangOrderStatus = [ Yii::$service->order->payment_status_pending, @@ -111,6 +104,7 @@ public function init() public function getCrtFile($domain) { if (isset($this->crt_file[$domain]) && !empty($this->crt_file[$domain])) { + return Yii::getAlias($this->crt_file[$domain]); } } @@ -126,7 +120,6 @@ public function receiveIpn($post) if ($this->verifySecurity($post)) { \Yii::info('verifySecurity', 'fecshop_debug'); // 验证数据是否已经发送 - //if ($this->isNotDuplicate()) { // 验证数据是否被篡改。 if ($this->isNotDistort()) { \Yii::info('updateOrderStatusByIpn', 'fecshop_debug'); @@ -137,7 +130,6 @@ public function receiveIpn($post) $suspected_fraud = Yii::$service->order->payment_status_suspected_fraud; $this->updateOrderStatusByIpn($suspected_fraud); } - // } } } @@ -155,6 +147,7 @@ protected function verifySecurity($post) $verifyReturn = $this->curlGet($verifyUrl); \Yii::info('verifyReturn:'.$verifyReturn, 'fecshop_debug'); if ($verifyReturn == 'VERIFIED') { + return true; } } @@ -174,11 +167,6 @@ protected function getVerifyUrl() $urlParamStr .= '&cmd=_notify-validate'; $urlParamStr = substr($urlParamStr, 1); $current_payment_method = Yii::$service->payment->getPaymentMethod(); - //if ($current_payment_method == $this->standard_payment_method) { - // $verifyUrl = Yii::$service->payment->getStandardWebscrUrl($this->standard_payment_method); - //} else { - // $verifyUrl = Yii::$service->payment->getExpressWebscrUrl($this->express_payment_method); - //} if ($this->_env == Yii::$service->payment->env_sanbox) { $verifyUrl = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; } else { @@ -221,8 +209,10 @@ protected function curlGet($url, $i = 0) if (!$httpResponse) { $i++; if ($i <= 5) { + return $this->curlGet($url, $i); } else { + return $httpResponse; } } @@ -230,34 +220,6 @@ protected function curlGet($url, $i = 0) return $httpResponse; } - /** - * paypal 可能发送多次IPN消息 - * 判断是否重复,如果不重复,把当前的插入。 - */ - /* - protected function isNotDuplicate() - { - $ipn = $this->_ipnMessageModel->find() - ->asArray() - ->where([ - 'txn_id'=>$this->_postData['txn_id'], - 'payment_status'=>$this->_postData['payment_status'], - ]) - ->one(); - if (is_array($ipn) && !empty($ipn)) { - return false; - } else { - $IpnMessage = new $this->_ipnMessageModelName(); - $IpnMessage->txn_id = $this->_postData['txn_id']; - $IpnMessage->payment_status = $this->_postData['payment_status']; - $IpnMessage->updated_at = time(); - $IpnMessage->save(); - - return true; - } - } - */ - /** * 验证订单数据是否被篡改。 * 通过订单号找到订单,查看是否存在 @@ -265,11 +227,9 @@ protected function isNotDuplicate() */ protected function isNotDistort() { - //Yii::$app->mylog->log("begin isNotDistort.."); $increment_id = $this->_postData['invoice']; $mc_gross = $this->_postData['mc_gross']; $mc_currency = $this->_postData['mc_currency']; - if ($increment_id && $mc_gross && $mc_currency) { $this->_order = Yii::$service->order->getByIncrementId($increment_id); if ($this->_order) { @@ -280,10 +240,9 @@ protected function isNotDistort() // if (round($currentCurrencyGrandTotal, 2) == round($mc_gross, 2)) { // 因为float精度问题,使用高精度函数进行比较,精度到2位小数 if(bccomp($currentCurrencyGrandTotal, $mc_gross, 2) == 0){ + return true; - } else { } - } else { } } } @@ -341,12 +300,6 @@ protected function updateOrderStatusByIpn($orderstatus = '') $updateArr['protection_eligibility'] = $this->_postData['protection_eligibility']; } $updateArr['updated_at'] = time(); - //$this->_order->updated_at = time(); - // 在service中不要出现事务代码,如果添加事务,请在调用层使用。 - //$innerTransaction = Yii::$app->db->beginTransaction(); - //try { - // 可以更改的订单状态 - if ($orderstatus) { $updateArr['order_status'] = $orderstatus; $this->_order->updateAll( @@ -357,11 +310,6 @@ protected function updateOrderStatusByIpn($orderstatus = '') ['in','order_status',$this->_allowChangOrderStatus] ] ); - // 指定了订单状态 - // $this->_order->order_status = $orderstatus; - // $this->_order->save(); - // $payment_status = strtolower($this->_postData['payment_status']); - // Yii::$app->mylog->log('save_'.$orderstatus); } else { $payment_status = strtolower($this->_postData['payment_status']); if ($payment_status == $this->payment_status_completed) { @@ -377,17 +325,11 @@ protected function updateOrderStatusByIpn($orderstatus = '') ['in','order_status',$this->_allowChangOrderStatus] ] ); - //$this->_order->order_status = Yii::$service->order->payment_status_processing; // 更新订单信息 - //$this->_order->save(); // 因为IPN消息可能不止发送一次,但是这里只允许一次, // 如果重复发送,$updateColumn 的更新返回值将为0 if (!empty($updateColumn)) { Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); - // 上面的函数已经执行下面的代码,因此注释掉。 - // $orderInfo = Yii::$service->order->getOrderInfoByIncrementId($this->_order['increment_id']); - // 发送新订单邮件 - // Yii::$service->email->order->sendCreateEmail($orderInfo); } } elseif ($payment_status == $this->payment_status_pending) { // pending 代表信用卡预付方式,需要等待paypal从信用卡中把钱扣除,因此订单状态是processing @@ -409,12 +351,8 @@ protected function updateOrderStatusByIpn($orderstatus = '') // 暂不处理 } } - //$innerTransaction->commit(); + return true; - //} catch (\Exception $e) { - // $innerTransaction->rollBack(); - //} - //return false; } // express 部分 @@ -432,6 +370,7 @@ public function getExpressCheckoutUrl($token) } else { $webscrUrl = 'https://www.paypal.com/cgi-bin/webscr'; } + return $webscrUrl.'?cmd=_express-checkout&token='.urlencode($token); } } @@ -443,12 +382,12 @@ public function getExpressCheckoutUrl($token) public function getStandardCheckoutUrl($token) { if ($token) { - // $webscrUrl = Yii::$service->payment->getStandardWebscrUrl($this->standard_payment_method); if ($this->_env == Yii::$service->payment->env_sanbox) { $webscrUrl = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; } else { $webscrUrl = 'https://www.paypal.com/cgi-bin/webscr'; } + return $webscrUrl.'?useraction=commit&cmd=_express-checkout&token='.urlencode($token); } } @@ -472,8 +411,6 @@ public function PPHttpPost5($methodName_, $nvpStr_, $i = 1) } else { $API_NvpUrl = 'https://api-3t.paypal.com/nvp'; } - - if ($current_payment_method == $this->standard_payment_method) { $ipn_url = Yii::$service->payment->getStandardIpnUrl($this->standard_payment_method); } else { @@ -482,10 +419,6 @@ public function PPHttpPost5($methodName_, $nvpStr_, $i = 1) // Set the API operation, version, and API signature in the request. $nvpreq = "METHOD=$methodName_&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_"; $nvpreq .= "&PAYMENTREQUEST_0_NOTIFYURL=".urlencode($ipn_url); - //echo $nvpreq; - //\Yii::info($nvpreq, 'fecshop_debug'); - - //exit; $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_URL, $API_NvpUrl); @@ -510,7 +443,6 @@ public function PPHttpPost5($methodName_, $nvpStr_, $i = 1) curl_setopt($ch, CURLOPT_HTTPHEADER, ['Connection: Close']); // Get response from the server. $httpResponse = curl_exec($ch); - //echo "

%%%%%".$httpResponse."%%%%%

"; if (!$httpResponse) { $i++; if ($i > 5) { @@ -519,18 +451,9 @@ public function PPHttpPost5($methodName_, $nvpStr_, $i = 1) } else { $httpResponse = $this->PPHttpPost5($methodName_, $nvpStr_, $i); } - } else { - //第一次获取数据失败,则再次获取。并返回、 - if ($i > 0) { - //return $httpResponse; - } } //paypal返回的是一系列的字符串,譬如:L_TIMESTAMP0=2014-11-08T01:51:13Z&L_TIMESTAMP1=2014-11-08T01:40:41Z&L_TIMESTAMP2=2014-11-08T01:40:40Z& //下面要做的是先把字符串通过&字符打碎成数组 - // - //echo "***************
"; - //echo urldecode($httpResponse); - //echo "
***************
"; $httpResponseAr = explode('&', urldecode($httpResponse)); $httpParsedResponseAr = []; foreach ($httpResponseAr as $i => $value) { @@ -558,7 +481,7 @@ public function getRequestUrlStrByArray($nvp_array) $str .= '&'.urlencode($k).'='.urlencode($v); } } - //echo $str;exit; + return $str; } @@ -576,17 +499,14 @@ public function getCheckoutPaymentNvpStr($token) // https://developer.paypal.com/docs/classic/api/merchant/SetExpressCheckout_API_Operation_NVP/ // 检查地址 $nvp_array['ADDROVERRIDE'] = 0; - //ADDROVERRIDE // 得到购物车的信息,通过购物车信息填写。 $orderInfo = Yii::$service->order->getInfoByPaymentToken($token); - //$cartInfo = Yii::$service->cart->getCartInfo(true); $currency = Yii::$service->page->currency->getCurrentCurrency(); $grand_total = Yii::$service->helper->format->number_format($orderInfo['grand_total']); $subtotal = Yii::$service->helper->format->number_format($orderInfo['subtotal']); $shipping_total = Yii::$service->helper->format->number_format($orderInfo['shipping_total']); $discount_amount= Yii::$service->helper->format->number_format($orderInfo['subtotal_with_discount']); $subtotal = $subtotal - $discount_amount; - $nvp_array['PAYMENTREQUEST_0_SHIPTOSTREET'] = $orderInfo['customer_address_street1'].' '.$orderInfo['customer_address_street2']; $nvp_array['PAYMENTREQUEST_0_SHIPTOCITY'] = $orderInfo['customer_address_city']; $nvp_array['PAYMENTREQUEST_0_SHIPTOSTATE'] = $orderInfo['customer_address_state_name']; @@ -594,7 +514,6 @@ public function getCheckoutPaymentNvpStr($token) $nvp_array['PAYMENTREQUEST_0_SHIPTOZIP'] = $orderInfo['customer_address_zip']; $nvp_array['PAYMENTREQUEST_0_SHIPTONAME'] = $orderInfo['customer_firstname'].' '.$orderInfo['customer_lastname']; $nvp_array['PAYMENTREQUEST_0_INVNUM'] = $orderInfo['increment_id']; - $nvp_array['PAYMENTREQUEST_0_CURRENCYCODE'] = $currency; $nvp_array['PAYMENTREQUEST_0_AMT'] = $grand_total; $nvp_array['PAYMENTREQUEST_0_ITEMAMT'] = $subtotal; @@ -603,7 +522,6 @@ public function getCheckoutPaymentNvpStr($token) $nvp_array['PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID'] = $this->seller_email; } $i = 0; - foreach ($orderInfo['products'] as $item) { $nvp_array['L_PAYMENTREQUEST_0_QTY'.$i] = $item['qty']; $nvp_array['L_PAYMENTREQUEST_0_NUMBER'.$i] = $item['sku']; @@ -614,9 +532,8 @@ public function getCheckoutPaymentNvpStr($token) } $nvp_array['L_PAYMENTREQUEST_0_NAME'.$i] = 'Discount'; $nvp_array['L_PAYMENTREQUEST_0_AMT'.$i] = '-'.$discount_amount; - //var_dump($nvp_array); $nvpStr = $this->getRequestUrlStrByArray($nvp_array); - //var_dump($nvpStr); + return $nvpStr; } @@ -644,8 +561,6 @@ public function getExpressTokenNvpStr($landingPage = 'Login', $return_url='', $c { $nvp_array = []; $nvp_array['LANDINGPAGE'] = $landingPage; - - if ($return_url) { $nvp_array['RETURNURL'] = $return_url; } else { @@ -661,13 +576,11 @@ public function getExpressTokenNvpStr($landingPage = 'Login', $return_url='', $c // 得到购物车的信息,通过购物车信息填写。 $cartInfo = Yii::$service->cart->getCartInfo(true); $currency = Yii::$service->page->currency->getCurrentCurrency(); - $grand_total = $cartInfo['grand_total']; $subtotal = $cartInfo['product_total']; $shipping_total = $cartInfo['shipping_cost']; $discount_amount = $cartInfo['coupon_cost']; $subtotal = $subtotal - $discount_amount; - $nvp_array['PAYMENTREQUEST_0_CURRENCYCODE'] = $currency; $nvp_array['PAYMENTREQUEST_0_AMT'] = $grand_total; $nvp_array['PAYMENTREQUEST_0_ITEMAMT'] = $subtotal; @@ -676,7 +589,6 @@ public function getExpressTokenNvpStr($landingPage = 'Login', $return_url='', $c $nvp_array['PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID'] = $this->seller_email; } $i = 0; - foreach ($cartInfo['products'] as $item) { $nvp_array['L_PAYMENTREQUEST_0_QTY'.$i] = $item['qty']; $nvp_array['L_PAYMENTREQUEST_0_NUMBER'.$i] = $item['sku']; @@ -716,15 +628,12 @@ public function getStandardTokenNvpStr($landingPage = 'Login', $return_url='', $ $nvp_array['VERSION'] = $this->version; // 得到购物车的信息,通过购物车信息填写。 $orderInfo = Yii::$service->order->getCurrentOrderInfo(); - //var_dump($orderInfo); $currency = $orderInfo['order_currency_code']; - $grand_total = Yii::$service->helper->format->number_format($orderInfo['grand_total']); $subtotal = Yii::$service->helper->format->number_format($orderInfo['subtotal']); $shipping_total = Yii::$service->helper->format->number_format($orderInfo['shipping_total']); $discount_amount= $orderInfo['subtotal_with_discount'] ? $orderInfo['subtotal_with_discount'] : 0; $subtotal = $subtotal - $discount_amount; - $nvp_array['PAYMENTREQUEST_0_CURRENCYCODE'] = $currency; $nvp_array['PAYMENTREQUEST_0_AMT'] = $grand_total; $nvp_array['PAYMENTREQUEST_0_ITEMAMT'] = $subtotal; @@ -733,21 +642,17 @@ public function getStandardTokenNvpStr($landingPage = 'Login', $return_url='', $ $nvp_array['PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID'] = $this->seller_email; } $i = 0; - foreach ($orderInfo['products'] as $item) { $nvp_array['L_PAYMENTREQUEST_0_QTY'.$i] = $item['qty']; $nvp_array['L_PAYMENTREQUEST_0_NUMBER'.$i] = $item['sku']; $nvp_array['L_PAYMENTREQUEST_0_AMT'.$i] = Yii::$service->helper->format->number_format($item['price']); $nvp_array['L_PAYMENTREQUEST_0_NAME'.$i] = $item['name']; - ; $nvp_array['L_PAYMENTREQUEST_0_CURRENCYCODE'.$i] = $currency; $i++; } $nvp_array['L_PAYMENTREQUEST_0_NAME'.$i] = 'Discount'; $nvp_array['L_PAYMENTREQUEST_0_AMT'.$i] = '-'.$discount_amount; - //var_dump($nvp_array); - //exit; return $this->getRequestUrlStrByArray($nvp_array); } @@ -766,6 +671,7 @@ public function getToken() $this->token = $token; } } + return $this->token; } @@ -784,6 +690,7 @@ public function getPayerID() $this->payerID = $payerID; } } + return $this->payerID; } @@ -804,7 +711,6 @@ public function updateOrderPayment($doCheckoutReturn, $token) } $updateArr = []; if ($order['increment_id']) { - //echo 'bbb'; $updateArr['txn_id'] = $doCheckoutReturn['PAYMENTINFO_0_TRANSACTIONID']; $updateArr['txn_type'] = $doCheckoutReturn['PAYMENTINFO_0_TRANSACTIONTYPE']; $PAYMENTINFO_0_AMT = $doCheckoutReturn['PAYMENTINFO_0_AMT']; @@ -844,10 +750,8 @@ public function updateOrderPayment($doCheckoutReturn, $token) if (!empty($updateColumn)) { // 执行订单支付成功后的事情。 Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']); - // 上面的函数已经执行下面的代码,因此注释掉。 - // $orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order['increment_id']); - // Yii::$service->email->order->sendCreateEmail($orderInfo); } + return true; } else { // 金额不一致,判定为欺诈 diff --git a/services/payment/Wxpay.php b/services/payment/Wxpay.php index 701a2f088..234d4bdac 100644 --- a/services/payment/Wxpay.php +++ b/services/payment/Wxpay.php @@ -48,6 +48,7 @@ public function init() parent::init(); $wxpayConfigFile = Yii::getAlias($this->configFile); if (!is_file($wxpayConfigFile)) { + throw new InvalidConfigException('wxpay config file:['.$wxpayConfigFile.'] is not exist'); } $appId = Yii::$app->store->get('payment_wxpay', 'wechat_service_app_id'); @@ -58,21 +59,13 @@ public function init() define('WX_APP_SECRET', $appSecret); define('WX_MCH_KEY', $mchKey); define('WX_MCH_ID', $mchId); - require_once($wxpayConfigFile); - $wxpayApiFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Api.php'); - //$wxpayDataFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Data.php'); $wxpayNotifyFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Notify.php'); - //$wxpayExceptionFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Exception.php'); - $wxpayNativePayFile = Yii::getAlias('@fecshop/lib/wxpay/example/WxPay.NativePay.php'); $wxpayLogFile = Yii::getAlias('@fecshop/lib/wxpay/example/log.php'); - require_once($wxpayApiFile); - //require_once($wxpayDataFile); require_once($wxpayNotifyFile); - //require_once($wxpayExceptionFile); require_once($wxpayNativePayFile); require_once($wxpayLogFile); //交易类型 @@ -85,10 +78,10 @@ public function init() $this->tradeType = "NATIVE"; } else { throw new InvalidConfigException('you must config param [devide] in payment wxpay service'); + return ; } } - $this->_allowChangOrderStatus = [ Yii::$service->order->payment_status_pending, Yii::$service->order->payment_status_processing, @@ -102,7 +95,6 @@ public function ipn() { $notifyFile = Yii::getAlias('@fecshop/services/payment/wxpay/notify.php'); require_once($notifyFile); - \Yii::info('begin ipn', 'fecshop_debug'); $notify = new \PayNotifyCallBack(); $notify->Handle(false); @@ -148,12 +140,14 @@ public function ipnUpdateOrder($data) \Yii::info('check order totla amouont['.($order_total_amount * 100).' == '.$total_fee.']', 'fecshop_debug'); // 微信支付的人民币单位为分 if(bccomp($order_total_amount * 100, $total_fee) !== 0){ + return false; } \Yii::info('updateOrderInfo', 'fecshop_debug'); // 更改订单状态 if ($this->updateOrderInfo($incrementId, $transaction_id, false)) { //支付成功调用服务执行订单状态改变,清空购物车和发送邮件操作 \Yii::info('updateOrderInfo Success', 'fecshop_debug'); + return true; } } @@ -195,7 +189,6 @@ public function getScanCodeStart() $input->SetTrade_type($this->tradeType); $input->SetProduct_id($trade_info['product_ids']); //此为二维码中包含的商品ID $result = $notify->GetPayUrl($input); - //var_dump($result);exit; /** * var_dump($result); * array(11) { @@ -213,7 +206,6 @@ public function getScanCodeStart() * } **/ //商户根据实际情况处理流程 - //var_dump($result);exit; if ($result['return_code'] == "FAIL") { Yii::$service->helper->errors->add('Api error: {return_msg}', ['return_msg' => $result['return_msg']]); @@ -224,6 +216,7 @@ public function getScanCodeStart() return false; } $scanCodeImgUrl =Yii::$service->url->getUrl('payment/wxpay/standard/qrcode', ['data' => urlencode($result['code_url'])]); + return [ // 二维码图片的url 'scan_code_img_url' => $scanCodeImgUrl, @@ -265,6 +258,7 @@ public function scanCodeCheckTradeIsSuccess($out_trade_no) $checkOrderStatus = Yii::$service->payment->wxpay->checkOrder($trade_state, $return_code, $trade_type, $out_trade_no, $total_amount, $seller_id, $auth_app_id); if ($checkOrderStatus) { + return $this->updateOrderInfo($out_trade_no, $trade_no); } } @@ -311,9 +305,11 @@ protected function getStartBizContentAndSetPaymentMethod() if (is_array($products)) { foreach ($products as $product) { $productIds = $product['product_id']; + break; } } + return [ 'increment_id' => $increment_id, 'total_amount' => $total_amount, @@ -333,16 +329,14 @@ public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_n { if ($trade_state != 'SUCCESS') { Yii::$service->helper->errors->add('request trade_state is not equle to SUCCESS'); + return false; } if ($return_code != 'SUCCESS') { Yii::$service->helper->errors->add('request return_code is not equle to SUCCESS'); + return false; } - //if ($trade_type != 'NATIVE') { - // Yii::$service->helper->errors->add('request trade_type is not equle to NATIVE'); - // return false; - //} if (!$this->_order) { $this->_order = Yii::$service->order->getByIncrementId($out_trade_no); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); @@ -356,11 +350,10 @@ public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_n $order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); if ((string)($order_total_amount * 100) != $total_amount) { //由于微信中是以分为单位所以必须乘以100,二维码页面也已经作了处理,单位都是分,$order_total_amount * 100要转为字符串再比较 Yii::$service->helper->errors->add('order increment id:{out_trade_no} , total_amount({total_amount}) is not equal to order_total_amount({order_total_amount})', ['out_trade_no'=>$out_trade_no , 'total_amount'=>$total_amount , 'order_total_amount'=>$order_total_amount ]); - //return ['o' => $order_total_amount * 100, 't' => $total_amount]; //测试时便于观察订单金额和微信实际支付的金额,生产环境要注释掉 + return false; } - return true; } @@ -380,6 +373,7 @@ protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true) if ($isClearCart) { Yii::$service->cart->clearCartProductAndCoupon(); } + return true; } } else { @@ -400,8 +394,6 @@ protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) $this->_order = Yii::$service->order->getByIncrementId($increment_id); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); } - - // 【优化后的代码 ##】 $orderstatus = Yii::$service->order->payment_status_confirmed; $updateArr['order_status'] = $orderstatus; $updateArr['txn_id'] = $trade_no; // 微信的交易号 @@ -417,29 +409,7 @@ protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } - // 【优化后的代码 ##】 - - /* 注释掉的原来代码,上面进行了优化,保证更改只有一次,这样发邮件也就只有一次了 - // 如果订单状态已经是processing,那么,不需要更改订单状态了。 - if ($this->_order['order_status'] == Yii::$service->order->payment_status_confirmed){ - - return true; - } - $order = $this->_order; - if (isset($order['increment_id']) && $order['increment_id']) { - // 如果支付成功,则更改订单状态为支付成功 - $order->order_status = Yii::$service->order->payment_status_confirmed; - $order->txn_id = $trade_no; // 微信的交易号 - // 更新订单信息 - $order->save(); - Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']); - // 得到当前的订单信息 - // $orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order['increment_id']); - // 发送新订单邮件 - // Yii::$service->email->order->sendCreateEmail($orderInfo); - return true; - } - */ + return true; } diff --git a/services/payment/WxpayH5.php b/services/payment/WxpayH5.php index 900882ec8..999d30d5c 100644 --- a/services/payment/WxpayH5.php +++ b/services/payment/WxpayH5.php @@ -48,6 +48,7 @@ public function init() parent::init(); $wxpayConfigFile = Yii::getAlias($this->configFile); if (!is_file($wxpayConfigFile)) { + throw new InvalidConfigException('wxpay config file:['.$wxpayConfigFile.'] is not exist'); } $appId = Yii::$app->store->get('payment_wxpay', 'wechat_service_app_id'); @@ -58,9 +59,7 @@ public function init() define('WX_APP_SECRET', $appSecret); define('WX_MCH_KEY', $mchKey); define('WX_MCH_ID', $mchId); - //echo $appId;exit; require_once($wxpayConfigFile); - $wxpayApiFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Api.php'); //$wxpayDataFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Data.php'); $wxpayNotifyFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Notify.php'); @@ -68,19 +67,14 @@ public function init() $wxpayJsApiPayPayFile = Yii::getAlias('@fecshop/lib/wxpay/example/WxPay.JsApiPay.php'); //$wxpayNativePayFile = Yii::getAlias('@fecshop/lib/wxpay/example/WxPay.NativePay.php'); $wxpayLogFile = Yii::getAlias('@fecshop/lib/wxpay/example/log.php'); - require_once($wxpayApiFile); - //require_once($wxpayDataFile); require_once($wxpayNotifyFile); - //require_once($wxpayExceptionFile); require_once($wxpayJsApiPayPayFile); require_once($wxpayLogFile); //交易类型 //JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里 //MICROPAY--刷卡支付,刷卡支付有单独的支付接口,不调用统一下单接口 - $this->tradeType = 'MWEB'; - - + $this->tradeType = 'MWEB'; $this->_allowChangOrderStatus = [ Yii::$service->order->payment_status_pending, Yii::$service->order->payment_status_processing, @@ -139,12 +133,14 @@ public function ipnUpdateOrder($data) \Yii::info('check order totla amouont['.($order_total_amount * 100).' == '.$total_fee.']', 'fecshop_debug'); // 微信支付的人民币单位为分 if(bccomp($order_total_amount * 100, $total_fee) !== 0){ + return false; } \Yii::info('updateOrderInfo', 'fecshop_debug'); // 更改订单状态 if ($this->updateOrderInfo($incrementId, $transaction_id, false)) { //支付成功调用服务执行订单状态改变,清空购物车和发送邮件操作 \Yii::info('updateOrderInfo Success', 'fecshop_debug'); + return true; } } @@ -153,43 +149,44 @@ public function ipnUpdateOrder($data) public function getOpenidUrl($baseUrl) { $tools = new \JsApiPay(); + return $tools->GetOpenidUrl($baseUrl); } - - function postXmlCurl($xml,$url,$second = 30){ - $ch = curl_init(); - //设置超时 - curl_setopt($ch, CURLOPT_TIMEOUT, $second); - curl_setopt($ch,CURLOPT_URL, $url); - curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); - curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE); - //设置 header - curl_setopt($ch, CURLOPT_HEADER, FALSE); - //要求结果为字符串且输出到屏幕上 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); - //post 提交方式 - curl_setopt($ch, CURLOPT_POST, TRUE); - curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); - //运行 curl - $data = curl_exec($ch); - //返回结果 - if($data){ - curl_close($ch); - return $data; - }else{ - $error = curl_errno($ch); - curl_close($ch); - echo "curl 出错,错误码:$error"."
"; - } + public function postXmlCurl($xml,$url,$second = 30){ + $ch = curl_init(); + //设置超时 + curl_setopt($ch, CURLOPT_TIMEOUT, $second); + curl_setopt($ch,CURLOPT_URL, $url); + curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); + curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE); + //设置 header + curl_setopt($ch, CURLOPT_HEADER, FALSE); + //要求结果为字符串且输出到屏幕上 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); + //post 提交方式 + curl_setopt($ch, CURLOPT_POST, TRUE); + curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); + //运行 curl + $data = curl_exec($ch); + //返回结果 + if($data){ + curl_close($ch); + + return $data; + }else{ + $error = curl_errno($ch); + curl_close($ch); + + echo "curl 出错,错误码:$error"."
"; } + } /** * @param $code | string 传递的微信code */ public function getScanCodeStart($code = "") { - // 根据订单得到json格式的微信支付参数。 $trade_info = $this->getStartBizContentAndSetPaymentMethod(); if (!$trade_info) { @@ -197,7 +194,6 @@ public function getScanCodeStart($code = "") return false; } - $money= $trade_info['total_amount'] * 100; //微信支付的单位为分,所以要乘以100; //充值金额 微信支付单位为分 $userip = Yii::$service->helper->getCustomerIp();; //获得用户设备 IP $appid = \WxPayConfig::APPID ; //应用 APPID @@ -210,11 +206,8 @@ public function getScanCodeStart($code = "") $spbill_create_ip = $userip; //IP $notify_url = Yii::$service->payment->getStandardIpnUrl(); //回调地址 $trade_type = $this->tradeType;//交易类型 具体看 API 里面有详细介绍 - //$scene_info ='{"h5_info":{"type":"Wap","wap_url":"http://qq52o.me","wap_name":"支付"}}';//场景信息 必要参数 - //echo $openId;exit; $wap_url = Yii::$service->url->homeUrl(); $scene_info ='{"h5_info":{"type":"Wap","wap_url":"'.$wap_url.'","wap_name":"'.$this->scanCodeBody.'"}}';//场景信息 必要参数 - $signA ="appid=$appid&attach=$out_trade_no&body=$body&mch_id=$mch_id&nonce_str=$nonce_str¬ify_url=$notify_url&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type"; $strSignTmp = $signA."&key=$key"; //拼接字符串 注意顺序微信有个测试网址 顺序按照他的来 直接点下面的校正测试 包括下面 XML 是否正确 $sign = strtoupper(MD5($strSignTmp)); // MD5 后转换成大写 @@ -233,110 +226,17 @@ public function getScanCodeStart($code = "") $sign ";//拼接成 XML 格式 $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信传参地址 - $dataxml = $this->postXmlCurl($post_data,$url); //后台 POST 微信传参地址 同时取得微信返回的参数 - + $dataxml = $this->postXmlCurl($post_data,$url); //后台 POST 微信传参地址 同时取得微信返回的参数 $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); //将微信返回的 XML 转换成数组 return $objectxml; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /* - - // 根据订单得到json格式的微信支付参数。 - $trade_info = $this->getStartBizContentAndSetPaymentMethod(); - if (!$trade_info) { - Yii::$service->helper->errors->add('generate wxpay bizContent error'); - - return false; - } - - $client_ip = Yii::$service->helper->getCustomerIp(); - //①、获取用户openid - $tools = new \JsApiPay(); - if (!$code) { - $openId = $tools->GetOpenid(); - } else { - $openId = $tools->GetOpenidByCode($code); - } - //echo $openId;exit; - $wap_url = Yii::$service->url->homeUrl(); - $wap_name = '微信H5支付'; - $scene_info ='{"h5_info":{"type":"Wap","wap_url":"'.$wap_url.'","wap_name":"'.wap_name.'"}}';//场景信息 必要参数 - - - //②、统一下单 - $input = new \WxPayUnifiedOrder(); - //$notify_url = Yii::$service->url->getUrl("payment/wxpayjsapi/ipn"); ////获取支付配置中的返回ipn url - $notify_url = Yii::$service->payment->getStandardIpnUrl(); - //$notify = new \NativePay(); - //$input = new \WxPayUnifiedOrder(); - $input->SetBody($this->scanCodeBody); - //$input->SetAttach("商店的额外的自定义数据"); - $input->SetAttach($trade_info['subject']); - $input->SetDevice_info($this->deviceInfo); // 设置设备号 - if ($trade_info['coupon_code']) { - $input->SetGoods_tag($trade_info['coupon_code']); //设置商品标记,代金券或立减优惠功能的参数 - } - $input->SetOut_trade_no($trade_info['increment_id']); // Fecshop 订单号 - $orderTotal = $trade_info['total_amount'] * 100; //微信支付的单位为分,所以要乘以100 - $input->SetTotal_fee($orderTotal); - $input->SetTime_start(date("YmdHis")); - - $input->SetTime_expire($this->getShangHaiExpireTime($this->expireTime)); - $input->SetNotify_url($notify_url); //通知地址 改成自己接口通知的接口,要有公网域名,测试时直接行动此接口会产生日志 - $input->SetTrade_type($this->tradeType); - $input->SetSpbill_create_ip($client_ip); - $input->SetSceneInfo($scene_info); - $input->SetProduct_id($trade_info['product_ids']); //此为二维码中包含的商品ID - //$input->SetOpenid($openId); - //var_dump($input); - $result = \WxPayApi::wapUnifiedOrder($input); - - return $result; - */ } //打印输出数组信息 - function printf_info($data) + public function printf_info($data) { foreach($data as $key=>$value){ + echo "$key : $value
"; } } @@ -363,9 +263,9 @@ public function scanCodeCheckTradeIsSuccess($out_trade_no) $seller_id = $result['mch_id']; $auth_app_id = $result['appid']; $trade_no = $result['transaction_id']; - $checkOrderStatus = Yii::$service->payment->wxpay->checkOrder($trade_state, $return_code, $trade_type, $out_trade_no, $total_amount, $seller_id, $auth_app_id); if ($checkOrderStatus) { + return $this->updateOrderInfo($out_trade_no, $trade_no); } } @@ -402,7 +302,6 @@ protected function getStartBizContentAndSetPaymentMethod() if (strlen($subject) > $this->subjectMaxLength) { $subject = mb_substr($subject, 0, $this->subjectMaxLength); } - //echo $subject; $increment_id = $currentOrderInfo['increment_id']; $base_grand_total = $currentOrderInfo['base_grand_total']; $total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); @@ -412,9 +311,11 @@ protected function getStartBizContentAndSetPaymentMethod() if (is_array($products)) { foreach ($products as $product) { $productIds = $product['product_id']; + break; } } + return [ 'increment_id' => $increment_id, 'total_amount' => $total_amount, @@ -434,14 +335,17 @@ public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_n { if ($trade_state != 'SUCCESS') { Yii::$service->helper->errors->add('request trade_state is not equle to SUCCESS'); + return false; } if ($return_code != 'SUCCESS') { Yii::$service->helper->errors->add('request return_code is not equle to SUCCESS'); + return false; } if ($trade_type != 'NATIVE') { Yii::$service->helper->errors->add('request trade_type is not equle to NATIVE'); + return false; } if (!$this->_order) { @@ -457,11 +361,10 @@ public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_n $order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); if ((string)($order_total_amount * 100) != $total_amount) { //由于微信中是以分为单位所以必须乘以100,二维码页面也已经作了处理,单位都是分,$order_total_amount * 100要转为字符串再比较 Yii::$service->helper->errors->add('order increment id:{out_trade_no} , total_amount({total_amount}) is not equal to order_total_amount({order_total_amount})', ['out_trade_no'=>$out_trade_no , 'total_amount'=>$total_amount , 'order_total_amount'=>$order_total_amount ]); - //return ['o' => $order_total_amount * 100, 't' => $total_amount]; //测试时便于观察订单金额和微信实际支付的金额,生产环境要注释掉 + return false; } - return true; } @@ -481,6 +384,7 @@ protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true) if ($isClearCart) { Yii::$service->cart->clearCartProductAndCoupon(); } + return true; } } else { @@ -501,8 +405,6 @@ protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) $this->_order = Yii::$service->order->getByIncrementId($increment_id); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); } - - // 【优化后的代码 ##】 $orderstatus = Yii::$service->order->payment_status_confirmed; $updateArr['order_status'] = $orderstatus; $updateArr['txn_id'] = $trade_no; // 微信的交易号 @@ -518,29 +420,7 @@ protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } - // 【优化后的代码 ##】 - - /* 注释掉的原来代码,上面进行了优化,保证更改只有一次,这样发邮件也就只有一次了 - // 如果订单状态已经是processing,那么,不需要更改订单状态了。 - if ($this->_order['order_status'] == Yii::$service->order->payment_status_confirmed){ - - return true; - } - $order = $this->_order; - if (isset($order['increment_id']) && $order['increment_id']) { - // 如果支付成功,则更改订单状态为支付成功 - $order->order_status = Yii::$service->order->payment_status_confirmed; - $order->txn_id = $trade_no; // 微信的交易号 - // 更新订单信息 - $order->save(); - Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']); - // 得到当前的订单信息 - // $orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order['increment_id']); - // 发送新订单邮件 - // Yii::$service->email->order->sendCreateEmail($orderInfo); - return true; - } - */ + return true; } diff --git a/services/payment/WxpayJsApi.php b/services/payment/WxpayJsApi.php index fd24223c6..c6ad5c096 100644 --- a/services/payment/WxpayJsApi.php +++ b/services/payment/WxpayJsApi.php @@ -17,7 +17,7 @@ use Monolog\Handler\IFTTTHandler; /** - * Payment wxpay services. + * Payment wxpay jsapi services. * @author Alex Chang<1692576541@qq.com> * @since 1.0 */ @@ -48,6 +48,7 @@ public function init() parent::init(); $wxpayConfigFile = Yii::getAlias($this->configFile); if (!is_file($wxpayConfigFile)) { + throw new InvalidConfigException('wxpay config file:['.$wxpayConfigFile.'] is not exist'); } $appId = Yii::$app->store->get('payment_wxpay', 'wechat_service_app_id'); @@ -78,8 +79,6 @@ public function init() //JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里 //MICROPAY--刷卡支付,刷卡支付有单独的支付接口,不调用统一下单接口 $this->tradeType = 'JSAPI'; - - $this->_allowChangOrderStatus = [ Yii::$service->order->payment_status_pending, Yii::$service->order->payment_status_processing, @@ -138,12 +137,14 @@ public function ipnUpdateOrder($data) \Yii::info('check order totla amouont['.($order_total_amount * 100).' == '.$total_fee.']', 'fecshop_debug'); // 微信支付的人民币单位为分 if(bccomp($order_total_amount * 100, $total_fee) !== 0){ + return false; } \Yii::info('updateOrderInfo', 'fecshop_debug'); // 更改订单状态 if ($this->updateOrderInfo($incrementId, $transaction_id, false)) { //支付成功调用服务执行订单状态改变,清空购物车和发送邮件操作 \Yii::info('updateOrderInfo Success', 'fecshop_debug'); + return true; } } @@ -152,6 +153,7 @@ public function ipnUpdateOrder($data) public function getOpenidUrl($baseUrl) { $tools = new \JsApiPay(); + return $tools->GetOpenidUrl($baseUrl); } @@ -167,7 +169,6 @@ public function getScanCodeStart($code = "") return false; } - //①、获取用户openid $tools = new \JsApiPay(); if (!$code) { @@ -175,8 +176,6 @@ public function getScanCodeStart($code = "") } else { $openId = $tools->GetOpenidByCode($code); } - //echo $openId;exit; - //②、统一下单 $input = new \WxPayUnifiedOrder(); //$notify_url = Yii::$service->url->getUrl("payment/wxpayjsapi/ipn"); ////获取支付配置中的返回ipn url @@ -209,18 +208,15 @@ public function getScanCodeStart($code = "") $isJsonFormat = false; } $jsApiParameters = $tools->GetJsApiParameters($order, $isJsonFormat); - //var_dump($jsApiParameters); //获取共享收货地址js函数参数 $editAddress = $tools->GetEditAddressParameters($isJsonFormat); - //var_dump($editAddress); - //echo '3333333333333333
'; + return [ 'jsApiParameters' => $jsApiParameters, 'editAddress' => $editAddress, 'total_amount' => $trade_info['total_amount'], 'increment_id' => $trade_info['increment_id'], - ]; - + ]; } //打印输出数组信息 @@ -256,6 +252,7 @@ public function scanCodeCheckTradeIsSuccess($out_trade_no) $checkOrderStatus = Yii::$service->payment->wxpay->checkOrder($trade_state, $return_code, $trade_type, $out_trade_no, $total_amount, $seller_id, $auth_app_id); if ($checkOrderStatus) { + return $this->updateOrderInfo($out_trade_no, $trade_no); } } @@ -292,7 +289,6 @@ protected function getStartBizContentAndSetPaymentMethod() if (strlen($subject) > $this->subjectMaxLength) { $subject = mb_substr($subject, 0, $this->subjectMaxLength); } - //echo $subject; $increment_id = $currentOrderInfo['increment_id']; $base_grand_total = $currentOrderInfo['base_grand_total']; $total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); @@ -302,9 +298,11 @@ protected function getStartBizContentAndSetPaymentMethod() if (is_array($products)) { foreach ($products as $product) { $productIds = $product['product_id']; + break; } } + return [ 'increment_id' => $increment_id, 'total_amount' => $total_amount, @@ -324,14 +322,17 @@ public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_n { if ($trade_state != 'SUCCESS') { Yii::$service->helper->errors->add('request trade_state is not equle to SUCCESS'); + return false; } if ($return_code != 'SUCCESS') { Yii::$service->helper->errors->add('request return_code is not equle to SUCCESS'); + return false; } if ($trade_type != 'NATIVE') { Yii::$service->helper->errors->add('request trade_type is not equle to NATIVE'); + return false; } if (!$this->_order) { @@ -347,11 +348,10 @@ public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_n $order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); if ((string)($order_total_amount * 100) != $total_amount) { //由于微信中是以分为单位所以必须乘以100,二维码页面也已经作了处理,单位都是分,$order_total_amount * 100要转为字符串再比较 Yii::$service->helper->errors->add('order increment id:{out_trade_no} , total_amount({total_amount}) is not equal to order_total_amount({order_total_amount})', ['out_trade_no'=>$out_trade_no , 'total_amount'=>$total_amount , 'order_total_amount'=>$order_total_amount ]); - //return ['o' => $order_total_amount * 100, 't' => $total_amount]; //测试时便于观察订单金额和微信实际支付的金额,生产环境要注释掉 + return false; } - return true; } @@ -371,6 +371,7 @@ protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true) if ($isClearCart) { Yii::$service->cart->clearCartProductAndCoupon(); } + return true; } } else { @@ -391,8 +392,6 @@ protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) $this->_order = Yii::$service->order->getByIncrementId($increment_id); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); } - - // 【优化后的代码 ##】 $orderstatus = Yii::$service->order->payment_status_confirmed; $updateArr['order_status'] = $orderstatus; $updateArr['txn_id'] = $trade_no; // 微信的交易号 @@ -408,35 +407,13 @@ protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } - // 【优化后的代码 ##】 - - /* 注释掉的原来代码,上面进行了优化,保证更改只有一次,这样发邮件也就只有一次了 - // 如果订单状态已经是processing,那么,不需要更改订单状态了。 - if ($this->_order['order_status'] == Yii::$service->order->payment_status_confirmed){ - - return true; - } - $order = $this->_order; - if (isset($order['increment_id']) && $order['increment_id']) { - // 如果支付成功,则更改订单状态为支付成功 - $order->order_status = Yii::$service->order->payment_status_confirmed; - $order->txn_id = $trade_no; // 微信的交易号 - // 更新订单信息 - $order->save(); - Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']); - // 得到当前的订单信息 - // $orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order['increment_id']); - // 发送新订单邮件 - // Yii::$service->email->order->sendCreateEmail($orderInfo); - return true; - } - */ + return true; } - // 支付宝的 标示 public function getWxpayHandle() { return 'wxpay_standard'; } + } diff --git a/services/payment/WxpayMicro.php b/services/payment/WxpayMicro.php index fce55489a..9a49d94f2 100644 --- a/services/payment/WxpayMicro.php +++ b/services/payment/WxpayMicro.php @@ -10,14 +10,13 @@ namespace fecshop\services\payment; -//use fecshop\models\mysqldb\IpnMessage; use fecshop\services\Service; use yii\base\InvalidConfigException; use Yii; use Monolog\Handler\IFTTTHandler; /** - * Payment wxpay services. + * Payment wxpay micro services. * @author Alex Chang<1692576541@qq.com> * @since 1.0 */ @@ -78,13 +77,10 @@ public function init() //JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里 //MICROPAY--刷卡支付,刷卡支付有单独的支付接口,不调用统一下单接口 $this->tradeType = 'JSAPI'; - - $this->_allowChangOrderStatus = [ Yii::$service->order->payment_status_pending, Yii::$service->order->payment_status_processing, ]; - } /** @@ -139,12 +135,14 @@ public function ipnUpdateOrder($data) \Yii::info('check order totla amouont['.($order_total_amount * 100).' == '.$total_fee.']', 'fecshop_debug'); // 微信支付的人民币单位为分 if(bccomp($order_total_amount * 100, $total_fee) !== 0){ + return false; } \Yii::info('updateOrderInfo', 'fecshop_debug'); // 更改订单状态 if ($this->updateOrderInfo($incrementId, $transaction_id, false)) { //支付成功调用服务执行订单状态改变,清空购物车和发送邮件操作 \Yii::info('updateOrderInfo Success', 'fecshop_debug'); + return true; } } @@ -153,6 +151,7 @@ public function ipnUpdateOrder($data) public function getOpenidUrl($baseUrl) { $tools = new \JsApiPay(); + return $tools->GetOpenidUrl($baseUrl); } @@ -168,25 +167,14 @@ public function getScanCodeStart() return false; } - //①、获取用户openid $tools = new \JsApiPay(); - //if (!$code) { - // $openId = $tools->GetOpenid(); - //} else { - // $openId = $tools->GetOpenidByCode($code); - //} $identity = Yii::$app->user->identity; $openId = $identity->wx_openid; - //②、统一下单 $input = new \WxPayUnifiedOrder(); $notify_url = Yii::$service->url->getUrl("payment/wxpayjsapi/ipn"); ////获取支付配置中的返回ipn url - //$notify_url = Yii::$service->payment->getStandardIpnUrl(); - //$notify = new \NativePay(); - //$input = new \WxPayUnifiedOrder(); $input->SetBody($this->scanCodeBody); - //$input->SetAttach("商店的额外的自定义数据"); $input->SetAttach($trade_info['subject']); $input->SetDevice_info('1000'); // 设置设备号 if ($trade_info['coupon_code']) { @@ -202,25 +190,18 @@ public function getScanCodeStart() $input->SetTrade_type($this->tradeType); $input->SetProduct_id($trade_info['product_ids']); //此为二维码中包含的商品ID $input->SetOpenid($openId); - // var_dump($input);exit; $order = \WxPayApi::unifiedOrder($input); - //echo '统一下单支付单信息
'; - //$this->printf_info($order); $isJsonFormat = false; - //var_dump($order);exit; $jsApiParameters = $tools->GetJsApiParameters($order, $isJsonFormat); - //var_dump($jsApiParameters); //获取共享收货地址js函数参数 $editAddress = $tools->GetEditAddressParameters($isJsonFormat); - //var_dump($editAddress); - //echo '3333333333333333
'; + return [ 'jsApiParameters' => $jsApiParameters, 'editAddress' => $editAddress, 'total_amount' => $trade_info['total_amount'], 'increment_id' => $trade_info['increment_id'], ]; - } //打印输出数组信息 @@ -256,6 +237,7 @@ public function scanCodeCheckTradeIsSuccess($out_trade_no) $checkOrderStatus = Yii::$service->payment->wxpay->checkOrder($trade_state, $return_code, $trade_type, $out_trade_no, $total_amount, $seller_id, $auth_app_id); if ($checkOrderStatus) { + return $this->updateOrderInfo($out_trade_no, $trade_no); } } @@ -292,7 +274,6 @@ protected function getStartBizContentAndSetPaymentMethod() if (strlen($subject) > $this->subjectMaxLength) { $subject = mb_substr($subject, 0, $this->subjectMaxLength); } - //echo $subject; $increment_id = $currentOrderInfo['increment_id']; $base_grand_total = $currentOrderInfo['base_grand_total']; $total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); @@ -302,9 +283,11 @@ protected function getStartBizContentAndSetPaymentMethod() if (is_array($products)) { foreach ($products as $product) { $productIds = $product['product_id']; + break; } } + return [ 'increment_id' => $increment_id, 'total_amount' => $total_amount, @@ -324,14 +307,17 @@ public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_n { if ($trade_state != 'SUCCESS') { Yii::$service->helper->errors->add('request trade_state is not equle to SUCCESS'); + return false; } if ($return_code != 'SUCCESS') { Yii::$service->helper->errors->add('request return_code is not equle to SUCCESS'); + return false; } if ($trade_type != 'NATIVE') { Yii::$service->helper->errors->add('request trade_type is not equle to NATIVE'); + return false; } if (!$this->_order) { @@ -347,11 +333,10 @@ public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_n $order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); if ((string)($order_total_amount * 100) != $total_amount) { //由于微信中是以分为单位所以必须乘以100,二维码页面也已经作了处理,单位都是分,$order_total_amount * 100要转为字符串再比较 Yii::$service->helper->errors->add('order increment id:{out_trade_no} , total_amount({total_amount}) is not equal to order_total_amount({order_total_amount})', ['out_trade_no'=>$out_trade_no , 'total_amount'=>$total_amount , 'order_total_amount'=>$order_total_amount ]); - //return ['o' => $order_total_amount * 100, 't' => $total_amount]; //测试时便于观察订单金额和微信实际支付的金额,生产环境要注释掉 + return false; } - return true; } @@ -371,6 +356,7 @@ protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true) if ($isClearCart) { Yii::$service->cart->clearCartProductAndCoupon(); } + return true; } } else { @@ -391,8 +377,6 @@ protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) $this->_order = Yii::$service->order->getByIncrementId($increment_id); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); } - - // 【优化后的代码 ##】 $orderstatus = Yii::$service->order->payment_status_confirmed; $updateArr['order_status'] = $orderstatus; $updateArr['txn_id'] = $trade_no; // 微信的交易号 @@ -408,29 +392,7 @@ protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } - // 【优化后的代码 ##】 - - /* 注释掉的原来代码,上面进行了优化,保证更改只有一次,这样发邮件也就只有一次了 - // 如果订单状态已经是processing,那么,不需要更改订单状态了。 - if ($this->_order['order_status'] == Yii::$service->order->payment_status_confirmed){ - - return true; - } - $order = $this->_order; - if (isset($order['increment_id']) && $order['increment_id']) { - // 如果支付成功,则更改订单状态为支付成功 - $order->order_status = Yii::$service->order->payment_status_confirmed; - $order->txn_id = $trade_no; // 微信的交易号 - // 更新订单信息 - $order->save(); - Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']); - // 得到当前的订单信息 - // $orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order['increment_id']); - // 发送新订单邮件 - // Yii::$service->email->order->sendCreateEmail($orderInfo); - return true; - } - */ + return true; } diff --git a/services/payment/wxpay/notify.php b/services/payment/wxpay/notify.php index 96214f548..aafffaea0 100644 --- a/services/payment/wxpay/notify.php +++ b/services/payment/wxpay/notify.php @@ -23,8 +23,10 @@ public function Queryorder($transaction_id) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") { + return true; } + return false; } @@ -33,17 +35,19 @@ public function NotifyProcess($data, &$msg) { \Yii::info("call back:" . json_encode($data), 'fecshop_debug'); $notfiyOutput = []; - if (!array_key_exists("transaction_id", $data)) { $msg = "输入参数不正确"; + return false; } //查询订单,判断订单真实性 if (!$this->Queryorder($data["transaction_id"])) { $msg = "订单查询失败"; + return false; } $arr = $this->getDataArray($data); + return \Yii::$service->payment->wxpay->ipnUpdateOrder($arr); } @@ -53,6 +57,7 @@ public function getDataArray($data) foreach ($data as $k => $v) { $arr[$k] = $v; } + return $arr; } } diff --git a/services/product/Attr.php b/services/product/Attr.php index bd7cce4ce..7dde93f08 100644 --- a/services/product/Attr.php +++ b/services/product/Attr.php @@ -23,16 +23,15 @@ * @property \fecshop\services\product\Stock $stock stock sub-service of product service * * @method getByPrimaryKey($primaryKey) get product model by primary key - * @see \fecshop\services\Product::actionGetByPrimaryKey() + * @see \fecshop\services\Product::getByPrimaryKey() * @method getEnableStatus() get enable status - * @see \fecshop\services\Product::actionGetEnableStatus() + * @see \fecshop\services\Product::getEnableStatus() * * @author Terry Zhao <2358269014@qq.com> * @since 1.0 */ class Attr extends Service { - /** * $storagePrex , $storage , $storagePath 为找到当前的storage而设置的配置参数 * 可以在配置中更改,更改后,就会通过容器注入的方式修改相应的配置值 @@ -51,19 +50,14 @@ class Attr extends Service */ protected $_attr; - public function init() { parent::init(); // 从数据库配置中得到值, 设置成当前service存储,是Mysqldb 还是 Mongodb - //$config = Yii::$app->store->get('service_db', 'category_and_product'); - //$this->storage = 'ProductMysqldb'; - //if ($config == Yii::$app->store->serviceMongodbName) { - // $this->storage = 'ProductMongodb'; - //} $currentService = $this->getStorageService($this); $this->_attr = new $currentService(); } + // 动态更改为mongodb model public function changeToMongoStorage() { @@ -80,7 +74,7 @@ public function changeToMysqlStorage() $this->_attr = new $currentService(); } - protected function actionGetEnableStatus() + public function getEnableStatus() { return $this->_attr->getEnableStatus(); } @@ -88,7 +82,7 @@ protected function actionGetEnableStatus() /** * get artile's primary key. */ - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return $this->_attr->getPrimaryKey(); } @@ -96,12 +90,12 @@ protected function actionGetPrimaryKey() /** * get artile model by primary key. */ - protected function actionGetByPrimaryKey($primaryKey) + public function getByPrimaryKey($primaryKey) { return $this->_attr->getByPrimaryKey($primaryKey); } - protected function actionColl($filter = '') + public function coll($filter = '') { return $this->_attr->coll($filter); } @@ -111,17 +105,17 @@ protected function actionColl($filter = '') * @param $originUrlKey|string , article origin url key. * save $data to cms model,then,add url rewrite info to system service urlrewrite. */ - protected function actionSave($one) + public function save($one) { return $this->_attr->save($one); } - protected function actionRemove($ids) + public function remove($ids) { return $this->_attr->remove($ids); } - protected function actionGetActiveColl($ids) + public function getActiveColl($ids) { return $this->_attr->remove($ids); } @@ -131,7 +125,6 @@ public function getActiveAllColl() return $this->_attr->getActiveAllColl(); } - public function getAttrTypes() { return [ @@ -145,10 +138,8 @@ public function getDbTypes() return [ 'String' => 'String', ]; - } - public function getDisplayTypes() { return [ @@ -159,14 +150,8 @@ public function getDisplayTypes() 'editSelect' => 'editSelect', 'select' => 'select', ]; - } - - - - - } diff --git a/services/product/AttrGroup.php b/services/product/AttrGroup.php index b6aaa0559..f600353aa 100644 --- a/services/product/AttrGroup.php +++ b/services/product/AttrGroup.php @@ -23,16 +23,15 @@ * @property \fecshop\services\product\Stock $stock stock sub-service of product service * * @method getByPrimaryKey($primaryKey) get product model by primary key - * @see \fecshop\services\Product::actionGetByPrimaryKey() + * @see \fecshop\services\Product::getByPrimaryKey() * @method getEnableStatus() get enable status - * @see \fecshop\services\Product::actionGetEnableStatus() + * @see \fecshop\services\Product::getEnableStatus() * * @author Terry Zhao <2358269014@qq.com> * @since 1.0 */ class AttrGroup extends Service { - /** * $storagePrex , $storage , $storagePath 为找到当前的storage而设置的配置参数 * 可以在配置中更改,更改后,就会通过容器注入的方式修改相应的配置值 @@ -51,16 +50,10 @@ class AttrGroup extends Service */ protected $_attrGroup; - public function init() { parent::init(); // 从数据库配置中得到值, 设置成当前service存储,是Mysqldb 还是 Mongodb - //$config = Yii::$app->store->get('service_db', 'category_and_product'); - //$this->storage = 'ProductMysqldb'; - //if ($config == Yii::$app->store->serviceMongodbName) { - // $this->storage = 'ProductMongodb'; - //} $currentService = $this->getStorageService($this); $this->_attrGroup = new $currentService(); } @@ -80,7 +73,7 @@ public function changeToMysqlStorage() $this->_attrGroup = new $currentService(); } - protected function actionGetEnableStatus() + public function getEnableStatus() { return $this->_attrGroup->getEnableStatus(); } @@ -88,7 +81,7 @@ protected function actionGetEnableStatus() /** * get artile's primary key. */ - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return $this->_attrGroup->getPrimaryKey(); } @@ -96,12 +89,12 @@ protected function actionGetPrimaryKey() /** * get artile model by primary key. */ - protected function actionGetByPrimaryKey($primaryKey) + public function getByPrimaryKey($primaryKey) { return $this->_attrGroup->getByPrimaryKey($primaryKey); } - protected function actionColl($filter = '') + public function coll($filter = '') { return $this->_attrGroup->coll($filter); } @@ -111,12 +104,12 @@ protected function actionColl($filter = '') * @param $originUrlKey|string , article origin url key. * save $data to cms model,then,add url rewrite info to system service urlrewrite. */ - protected function actionSave($one) + public function save($one) { return $this->_attrGroup->save($one); } - protected function actionRemove($ids) + public function remove($ids) { return $this->_attrGroup->remove($ids); } @@ -124,7 +117,6 @@ protected function actionRemove($ids) public function getActiveAllColl() { return $this->_attrGroup->getActiveAllColl(); - } diff --git a/services/product/BestSell.php b/services/product/BestSell.php index 46f5370b8..f90dd75a2 100644 --- a/services/product/BestSell.php +++ b/services/product/BestSell.php @@ -22,7 +22,7 @@ class BestSell extends Service /** * 得到全部产品中热销的产品 */ - protected function actionGetCategoryProduct() + public function getCategoryProduct() { return 'category best sell product'; } @@ -30,7 +30,7 @@ protected function actionGetCategoryProduct() /** * 得到全部产品中热销的产品 */ - protected function actionGetProduct() + public function getProduct() { } } diff --git a/services/product/Brand.php b/services/product/Brand.php index 6e8d96f8c..96df6924b 100644 --- a/services/product/Brand.php +++ b/services/product/Brand.php @@ -58,6 +58,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_modelName(); } } @@ -89,7 +90,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($one); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -175,7 +176,6 @@ public function getAllBrandIdAndNames() 'fetchAll' => true, 'asArray' => true, ]; - $data = $this->coll($filter); $arr = []; if (is_array($data['coll']) && !empty($data['coll'])) { @@ -205,8 +205,4 @@ public function getBrandNameById($brandId) - - - - } diff --git a/services/product/Brandcategory.php b/services/product/Brandcategory.php index 08b986f47..2d037f19e 100644 --- a/services/product/Brandcategory.php +++ b/services/product/Brandcategory.php @@ -58,6 +58,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_modelName(); } } @@ -89,7 +90,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($one); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -104,7 +105,6 @@ public function save($one) { $currentDateTime = \fec\helpers\CDate::getCurrentDateTime(); $primaryVal = isset($one[$this->getPrimaryKey()]) ? $one[$this->getPrimaryKey()] : ''; - if ($primaryVal) { $model = $this->_model->findOne($primaryVal); if (!$model) { @@ -174,7 +174,6 @@ public function getBrandCategoryIdAndNames() 'fetchAll' => true, 'asArray' => true, ]; - $data = $this->coll($filter); $arr = []; if (is_array($data['coll']) && !empty($data['coll'])) { diff --git a/services/product/Favorite.php b/services/product/Favorite.php index d3d0a0314..e315eafc5 100644 --- a/services/product/Favorite.php +++ b/services/product/Favorite.php @@ -125,7 +125,7 @@ public function updateUserFavoriteCount($user_id = '') * 'asArray' => true, * ] */ - public function actionList($filter) + public function list($filter) { return $this->_favorite->list($filter); } diff --git a/services/product/Image.php b/services/product/Image.php index a14cd9902..e8533cbc4 100644 --- a/services/product/Image.php +++ b/services/product/Image.php @@ -63,7 +63,6 @@ class Image extends Service protected $_md5WaterImgPath; - public function init() { parent::init(); @@ -76,7 +75,7 @@ public function init() /** * 得到保存产品图片所在相对根目录的url路径. */ - protected function actionGetBaseUrl() + public function getBaseUrl() { return Yii::$service->image->GetImgUrl($this->imageFloder, 'common'); } @@ -84,7 +83,7 @@ protected function actionGetBaseUrl() /** * 得到保存产品图片所在相对根目录的文件夹路径. */ - protected function actionGetBaseDir() + public function getBaseDir() { return Yii::$service->image->GetImgDir($this->imageFloder, 'common'); } @@ -92,7 +91,7 @@ protected function actionGetBaseDir() /** * 通过产品图片的相对路径得到产品图片的url. */ - protected function actionGetUrl($str) + public function getUrl($str) { return Yii::$service->image->GetImgUrl($this->imageFloder.$str, 'common'); } @@ -100,7 +99,7 @@ protected function actionGetUrl($str) /** * 通过产品图片的相对路径得到产品图片的绝对路径. */ - protected function actionGetDir($str) + public function getDir($str) { return Yii::$service->image->GetImgDir($this->imageFloder.$str, 'common'); } @@ -112,7 +111,7 @@ protected function actionGetDir($str) * return , if success ,return image saved relative file path , like '/b/i/big.jpg' * if fail, reutrn false; */ - protected function actionSaveProductUploadImg($FILE) + public function saveProductUploadImg($FILE) { Yii::$service->image->imageFloder = $this->imageFloder; Yii::$service->image->allowImgType = $this->allowImgType; @@ -126,7 +125,7 @@ protected function actionSaveProductUploadImg($FILE) /** * 获取产品默认图片的完整URL */ - protected function actionDefautImg() + public function defautImg() { if (!$this->_defaultImg) { $this->_defaultImg = $this->getUrl($this->defaultImg); @@ -142,7 +141,7 @@ protected function actionDefautImg() * @param $isWatered | Boolean , 产品图片是否打水印。 * 获取相应尺寸的产品图片。 */ - protected function actionGetResize($imageVal, $imgResize, $isWatered = false) + public function getResize($imageVal, $imgResize, $isWatered = false) { list($newPath, $newUrl) = $this->getNewPathAndUrl($imageVal, $imgResize, $isWatered); @@ -150,10 +149,10 @@ protected function actionGetResize($imageVal, $imgResize, $isWatered = false) } /** - * 和上面的方法 actionGetResize 功能类似, actionGetResize是得到按照图片尺寸resize后的图片的url。 + * 和上面的方法 getResize 功能类似, getResize是得到按照图片尺寸resize后的图片的url。 * 本函数是得到resize后图片的 完整文件路径 (绝对文件地址) */ - protected function actionGetResizeDir($imageVal, $imgResize, $isWatered = false) + public function getResizeDir($imageVal, $imgResize, $isWatered = false) { list($newPath, $newUrl) = $this->getNewPathAndUrl($imageVal, $imgResize, $isWatered); @@ -167,7 +166,7 @@ protected function actionGetResizeDir($imageVal, $imgResize, $isWatered = false) * @param $isWatered | Boolean , 产品图片是否打水印。 * 获取相应尺寸的产品图片。 */ - protected function actionGetNewPathAndUrl($imageVal, $imgResize, $isWatered = false) + public function getNewPathAndUrl($imageVal, $imgResize, $isWatered = false) { $originImgPath = $this->getDir($imageVal); if (!file_exists($originImgPath)) { @@ -207,7 +206,6 @@ protected function getProductNewPath($imageVal, $imgResize, $waterImgPath) //echo $waterImgPath;exit; $this->_md5WaterImgPath = md5($waterImgPath); } - $baseDir = '/cache/'.$this->_md5WaterImgPath; if (is_array($imgResize)) { list($width, $height) = $imgResize; @@ -215,7 +213,6 @@ protected function getProductNewPath($imageVal, $imgResize, $waterImgPath) $width = $imgResize; $height = '0'; } - $imageArr = explode('/', $imageVal); $dirArr = ['cache', $this->_md5WaterImgPath, $width, $height]; foreach ($imageArr as $igf) { @@ -227,8 +224,10 @@ protected function getProductNewPath($imageVal, $imgResize, $waterImgPath) if ($createDir) { $newPath = $this->getBaseDir().$baseDir .'/'.$width.'/'.$height.$imageVal; $newUrl = $this->getBaseUrl().$baseDir .'/'.$width.'/'.$height.$imageVal; + return [$newPath, $newUrl]; } else { + return []; } } diff --git a/services/product/Info.php b/services/product/Info.php index 217c353a0..ee7b137d4 100644 --- a/services/product/Info.php +++ b/services/product/Info.php @@ -21,14 +21,6 @@ */ class Info extends Service { - - //protected $_productModelName = '\fecshop\models\mongodb\Product'; - //protected $_productModel; - - //public function __construct(){ - //list($this->_productModelName,$this->_productModel) = \Yii::mapGet($this->_productModelName); - //} - /** * @param $custome_option | Array * $custome_option = [ @@ -60,6 +52,7 @@ public function getCustomOptionSkuByValue($custome_option) public function validateProductCustomOption($custom_option, $product_custom_option) { if (empty($product_custom_option) && empty($custom_option)) { + return true; // 都为空,说明不需要验证。 } if ($custom_option) { @@ -72,6 +65,7 @@ public function validateProductCustomOption($custom_option, $product_custom_opti } foreach ($product_custom_option as $p_sku => $option) { if ($p_sku == $co_sku) { + return true; } } @@ -119,6 +113,7 @@ public function getProductCOSku($custom_option_arr, $product_custom_option) } } if ($bool) { + return $co_sku; } } diff --git a/services/product/Price.php b/services/product/Price.php index 30a297774..36bec1f43 100644 --- a/services/product/Price.php +++ b/services/product/Price.php @@ -47,10 +47,11 @@ public function init() * @param $price | Float 产品的价格 * 得到当前货币状态下的产品的价格信息。 */ - protected function actionFormatPrice($price) + public function formatPrice($price) { $currencyInfo = $this->getCurrentInfo(); $price = Yii::$service->helper->format->number_format($price * $currencyInfo['rate']); + return [ 'code' => $currencyInfo['code'], 'symbol' => $currencyInfo['symbol'], @@ -62,7 +63,7 @@ protected function actionFormatPrice($price) * @param $price | Float 产品价格 * @return String , 带有相应货币符号的价格 */ - protected function actionFormatSamplePrice($price) + public function formatSamplePrice($price) { $currencyInfo = $this->getCurrentInfo(); $price = $price * $currencyInfo['rate']; @@ -86,7 +87,7 @@ protected function actionFormatSamplePrice($price) * * @return float */ - protected function actionGetFinalPrice( + public function getFinalPrice( $price, $special_price, $special_from, @@ -113,12 +114,11 @@ protected function actionGetFinalPrice( * @param $format | Int , 返回的价格的格式,0代表为美元格式,1代表为当前货币格式,2代表美元和当前货币格式都有 * 通过产品以及个数,custonOptionSku 得到产品的最终价格 */ - protected function actionGetCartPriceByProductId($productId, $qty, $custom_option_sku, $format = 1) + public function getCartPriceByProductId($productId, $qty, $custom_option_sku, $format = 1) { $product = Yii::$service->product->getByPrimaryKey($productId); $custom_option_price = 0; $status = isset($product['status']) ? $product['status'] : 0; - if ($product['price'] && Yii::$service->product->isActive($status)) { $price = $product['price']; $special_price = isset($product['special_price']) ? $product['special_price'] : 0; @@ -126,7 +126,6 @@ protected function actionGetCartPriceByProductId($productId, $qty, $custom_optio $special_to = isset($product['special_to']) ? $product['special_to'] : ''; $tier_price = isset($product['tier_price']) ? $product['tier_price'] : []; $custom_option = isset($product['custom_option']) ? $product['custom_option'] : ''; - if (!empty($custom_option) && $custom_option_sku && isset($custom_option[$custom_option_sku])) { if ($co = $custom_option[$custom_option_sku]) { $custom_option_price = isset($co['price']) ? $co['price'] : 0; @@ -162,7 +161,7 @@ protected function actionGetCartPriceByProductId($productId, $qty, $custom_optio * ]; * @param $format | Int , 返回的价格的格式,0代表为美元格式,1代表为当前货币格式,2代表美元和当前货币格式都有 */ - protected function actionGetCartPrice( + public function getCartPrice( $price, $special_price, $special_from, @@ -177,7 +176,6 @@ protected function actionGetCartPrice( } else { $return_price = $price; } - if ($qty > 1) { $return_price = $this->getTierPrice($qty, $tier_price, $return_price); } @@ -194,6 +192,7 @@ protected function actionGetCartPrice( 'curr_price' => $format_price, ]; } else { + return $return_price; } } @@ -208,9 +207,10 @@ protected function actionGetCartPrice( * ]; * 传递过来的tier_price 数组,必须是按照qty进行排序好了的数组 */ - protected function actionGetTierPrice($qty, $tier_price_arr, $price) + public function getTierPrice($qty, $tier_price_arr, $price) { if ($qty <= 1) { + return $price; } $t_price = $price; @@ -218,14 +218,16 @@ protected function actionGetTierPrice($qty, $tier_price_arr, $price) foreach ($tier_price_arr as $one) { $t_qty = $one['qty']; $t_price = $one['price']; - if ($t_qty <= $qty) { $parent_price = $t_price; + continue; } else { if ($parent_price) { + return $parent_price; } else { + return $price; } } @@ -246,24 +248,28 @@ protected function actionGetTierPrice($qty, $tier_price_arr, $price) * @param $special_to | Int 产品的特检结束时间 * @return bool */ - protected function actionSpecialPriceisActive($price, $special_price, $special_from, $special_to) + public function specialPriceisActive($price, $special_price, $special_from, $special_to) { if (!$special_price || $special_price == 0.00) { // 浮点数需要这样判断float 0 + return false; } if ($this->ifSpecialPriceGtPriceFinalPriceEqPrice) { if ($special_price > $price) { + return false; } } $nowTimeStamp = time(); if ($special_from) { if ($special_from > $nowTimeStamp) { + return false; } } if ($special_to) { if ($special_to < $nowTimeStamp) { + return false; } } @@ -291,7 +297,7 @@ protected function getCurrentInfo() * @param $special_to | Int 产品的特检结束时间 * @return $return | Array 产品的价格信息 */ - protected function actionGetCurrentCurrencyProductPriceInfo($price, $special_price, $special_from, $special_to) + public function getCurrentCurrencyProductPriceInfo($price, $special_price, $special_from, $special_to) { $price = (float)$price; $special_price = (float)$special_price; diff --git a/services/product/ProductApi.php b/services/product/ProductApi.php index ff71affe5..dc9c57c5a 100644 --- a/services/product/ProductApi.php +++ b/services/product/ProductApi.php @@ -51,6 +51,7 @@ protected function checkPostDataRequireAndInt($post) $model = $this->_productModel; if (empty($post) || !is_array($post)) { $this->_error[] = 'post data is empty or is not array'; + return ; } // 产品名字:【必填】 【多语言属性】 @@ -117,7 +118,6 @@ protected function checkPostDataRequireAndInt($post) if ($category) { $this->_param['category'] = $category; } - // 选填, 是否下架, 如果不存在,或者不合法,则会被设置成有库存状态 $is_in_stock = $post['is_in_stock']; $allow_stock_arr = [$model::IS_IN_STOCK,$model::OUT_STOCK]; @@ -182,8 +182,6 @@ protected function checkPostDataRequireAndInt($post) $this->_error[] = '[tier_price] data must be array'; } } - - // 选填 开始时间只要“年-月-日”部分,其他部分去除,然后取00:00:00的数据 $new_product_from = $post['new_product_from']; if ($new_product_from) { @@ -222,112 +220,6 @@ protected function checkPostDataRequireAndInt($post) } else { $this->_param['attr_group'] = $attr_group; } - /** - * 选填 当选择淘宝模式的产品时,一行数据是一个spu,各个sku的图片,库存,浮动价格,各个自定义属性的值等,就会存储到这个属性里面 - * 譬如: - * "custom_option": { - * "red-s-s2-s3": { - * "my_color": "red", - * "my_size": "S", - * "my_size2": "S2", - * "my_size3": "S3", - * "sku": "red-s-s2-s3", - * "qty": NumberInt(99999), - * "price": 0, - * "image": "/2/01/20161024170457_10036.jpg" - * }, - * "red-m-s2-s3": { - * "my_color": "red", - * "my_size": "M", - * "my_size2": "S2", - * "my_size3": "S3", - * "sku": "red-m-s2-s3", - * "qty": NumberInt(99999), - * "price": 0, - * "image": "/2/01/20161024170457_10036.jpg" - * }, - * "red-l-s2-s3": { - * "my_color": "red", - * "my_size": "L", - * "my_size2": "S2", - * "my_size3": "S3", - * "sku": "red-l-s2-s3", - * "qty": NumberInt(99999), - * "price": 0, - * "image": "/2/01/20161024170457_10036.jpg" - * } - * } - * 需要进行如下检查: - * 1. 图片地址是否存在,不存在则报错 - * 2. sku 存在,且在当前数组中sku 重复的,将会被去除 - * 3. 通过属性组 attr_group 找到相应的custom option,查看里面的值,在这里是否都存在 - * 4. qty 是否存在,不存在,则初始化为0 , - * 5. price是否存在,不存在则初始化为0, - * 6. 数组的key,需要和sku相等,譬如 red-l-s2-s3 要等于下面的 "sku": "red-l-s2-s3" - * - */ - /* - $custom_option = $post['custom_option']; - if (!empty($custom_option) && is_array($custom_option) && isset($customAttrGroup[$attr_group]['custom_options']) && $customAttrGroup[$attr_group]['custom_options']) { - $custom_option_arr = []; - // 1. - // 该属性组对应的 custom option 的数据配置结构 - $attr_group_config = $customAttrGroup[$attr_group]['custom_options']; - foreach ($custom_option as $key => $info) { - // 1. 图片地址是否存在,不存在则报错 - if (!isset($info['image']) || !$info['image']) { - $this->_error[] = 'custom option: image can not empty'; - } - // 2.sku 存在 - if (!isset($info['sku']) || !$info['sku']) { - $this->_error[] = 'custom option: sku can not empty'; - } - // 4. qty 是否存在,不存在,则初始化为0 - $info['qty'] = (int)$info['qty']; - if (!$info['qty']) { - $info['qty'] = 0; - } - // 5. price是否存在,不存在则初始化为0, - $info['price'] = (float)$info['price']; - if (!$info['price']) { - $info['price'] = 0; - } - // 3. 通过属性组 attr_group 找到相应的custom option,查看里面的值,在这里是否都存在 - if (is_array($attr_group_config)) { - // 遍历 custom option 的数据配置结构 - foreach ($attr_group_config as $attrKey => $custom_option_info) { - // 当前行数据中,是否符合 数据配置结构 - $val = ''; - if (isset($info[$attrKey]) && $info[$attrKey]) { - $val = $info[$attrKey]; - } else { - $this->_error[] = '[custom option error]: (attr_group:'.$attr_group.') attr['.$attrKey.'] is exist in config file ,but current data is empty'; - // error: 缺失 $attrKey 存在数据配置结构中,但是当前的插入数据中不存在这个属性。 - } - if (isset($custom_option_info['display']['data']) && is_array($custom_option_info['display']['data'])) { - $attr_group_config_val_arr = $custom_option_info['display']['data']; - if (in_array($val, $attr_group_config_val_arr)) { - - // success - } else { - $this->_error[] = '[custom option error]: (attr_group:'.$attr_group.') attr['.$attrKey.':'.$val.'] must exist in array ['.implode(',', $attr_group_config_val_arr).'] '; - // error:$attrKey 这个属性在当前的插入数据中存在,但是值不合法,值必须存在于 "数据配置结构" 中对应的数据列表中 - } - } else { - $this->_error[] = '[custom option config error]: (attr_group:'.$attr_group.') attr['.$attrKey.'] config is not correct , it must exist: [\'display\'][\'data\']'; - } - } - } else { - $this->_error[] = '[custom option config error]: (attr_group:'.$attr_group.') , it must be array'; - } - $custom_option_arr[$info['sku']] = $info; - } - if (!empty($custom_option_arr)) { - $this->_param['custom_option'] = $custom_option_arr; - } - } - */ - // 选填 $remark = $post['remark']; if ($remark) { @@ -348,9 +240,6 @@ protected function checkPostDataRequireAndInt($post) if ($see_also_see_sku) { $this->_param['see_also_see_sku'] = $see_also_see_sku; } - - - // 选填 产品状态 $status = $post['status']; $allowStatus = [$model::STATUS_ENABLE,$model::STATUS_DISABLE]; @@ -363,7 +252,6 @@ protected function checkPostDataRequireAndInt($post) if ($url_key) { $this->_param['url_key'] = $url_key; } - /** * 选填 产品的图片 * 图片的格式如下: @@ -473,6 +361,7 @@ public function insertByPost($post = []) } $this->checkPostDataRequireAndInt($post); if (!empty($this->_error)) { + return [ 'code' => 400, 'message' => '', @@ -495,6 +384,7 @@ public function insertByPost($post = []) $saveData['id'] = (string)$saveData['_id']; unset($saveData['_id']); } + return [ 'code' => 200, 'message' => 'add product success', @@ -503,6 +393,7 @@ public function insertByPost($post = []) ] ]; } else { + return [ 'code' => 400, 'message' => 'save category fail', diff --git a/services/product/ProductMongodb.php b/services/product/ProductMongodb.php index f92b9bc6b..cb61243fc 100644 --- a/services/product/ProductMongodb.php +++ b/services/product/ProductMongodb.php @@ -44,14 +44,17 @@ public function getPrimaryKey() public function getEnableStatus() { $model = $this->_productModel; + return $model::STATUS_ENABLE; } public function getByPrimaryKey($primaryKey = null) { if ($primaryKey) { + return $this->_productModel->findOne($primaryKey); } else { + return new $this->_productModelName(); } } @@ -80,6 +83,7 @@ public function getBySku($sku, $returnArr = true) } $primaryKey = $this->getPrimaryKey(); if (isset($product[$primaryKey]) && !empty($product[$primaryKey])) { + return $product; } } @@ -166,7 +170,6 @@ public function coll($filter = '') public function spuCollData($select, $spuAttrArr, $spu) { $select = array_merge($select, $spuAttrArr); - //var_dump($select);exit; $filter = [ 'select' => $select, 'where' => [ @@ -280,7 +283,6 @@ public function getCategoryProductIds($product_id_arr, $category_id) foreach ($product_id_arr as $id) { $mongoIds[] = new \MongoDB\BSON\ObjectId($id); } - //var_dump($mongoIds); $query->where(['in', $this->getPrimaryKey(), $mongoIds]); $query->andWhere(['category'=>$category_id]); $data = $query->all(); @@ -333,7 +335,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') $spuAttrArr[] = $groupSpuOne['name']; } } - if ($primaryVal) { $model = $this->_productModel->findOne($primaryVal); if (!$model) { @@ -341,7 +342,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') return false; } - //验证sku 是否重复 $product_one = $this->_productModel->find()->asArray()->where([ '<>', $this->getPrimaryKey(), (new \MongoDB\BSON\ObjectId($primaryVal)), @@ -353,7 +353,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') return false; } - // spu 下面的各个sku的spu属性不能相同 if (!empty($spuAttrArr)) { $product_mode = $this->_productModel->find()->asArray()->where([ @@ -362,10 +361,8 @@ public function save($one, $originUrlKey = 'catalog/product/index') 'spu' => $one['spu'], ]); foreach ($spuAttrArr as $sar) { - //var_dump([$sar => $one[$sar]]); $product_mode->andWhere([$sar => $one[$sar]]); } - $product_one = $product_mode->one(); if ($product_one['sku']) { Yii::$service->helper->errors->add('product Spu of the same22, Spu attributes cannot be the same'); @@ -388,7 +385,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') return false; } - if (!empty($spuAttrArr)) { $product_mode = $this->_productModel->find()->asArray()->where([ 'spu' => $one['spu'], @@ -396,7 +392,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') foreach ($spuAttrArr as $sar) { $product_mode->andWhere([$sar => $one[$sar]]); } - $product_one = $product_mode->one(); if ($product_one['sku']) { Yii::$service->helper->errors->add('product Spu of the same, Spu attributes cannot be the same'); @@ -404,31 +399,17 @@ public function save($one, $originUrlKey = 'catalog/product/index') return false; } } - } - $model->updated_at = time(); // 计算出来产品的最终价格。 $one['final_price'] = Yii::$service->product->price->getFinalPrice($one['price'], $one['special_price'], $one['special_from'], $one['special_to']); $one['score'] = (int) $one['score']; unset($one['_id']); unset($one['custom_option']); - /** - * 如果 $one['custom_option'] 不为空,则计算出来库存总数,填写到qty - */ - //if (is_array($one['custom_option']) && !empty($one['custom_option'])) { - // $custom_option_qty = 0; - // foreach ($one['custom_option'] as $co_one) { - // $custom_option_qty += $co_one['qty']; - // } - // $one['qty'] = $custom_option_qty; - //} /** * 保存产品 */ - //var_dump($one);exit; $saveStatus = Yii::$service->helper->ar->save($model, $one); - // 自定义url部分 if ($originUrlKey) { $originUrl = $originUrlKey.'?'.$this->getPrimaryKey() .'='. $primaryVal; @@ -438,7 +419,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') $model->url_key = $urlKey; $model->save(); } - $product_id = $model->{$this->getPrimaryKey()}; /** * 更新产品库存。 @@ -452,7 +432,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') return $model; } - /** * @param $one|array , 产品数据数组 * 用于将mysql的数据,同步到mongodb中 @@ -477,8 +456,6 @@ public function sync($one) $primaryVal = new \MongoDB\BSON\ObjectId(); $model->{$this->getPrimaryKey()} = $primaryVal; } - - // 保存mongodb表中的产品id到字段origin_mongo_id $origin_mysql_id = $one['id']; $model->origin_mysql_id = $origin_mysql_id; @@ -491,34 +468,20 @@ public function sync($one) /** * 如果 $one['custom_option'] 不为空,则计算出来库存总数,填写到qty */ - //if (is_array($one['custom_option']) && !empty($one['custom_option'])) { - // $custom_option_qty = 0; - // foreach ($one['custom_option'] as $co_one) { - // $custom_option_qty += $co_one['qty']; - // } - // $one['qty'] = $custom_option_qty; - //} - /** * 保存产品 */ - //$one = $this->serializeSaveData($one); // 得到对应的mongodb的分类id数组 - //var_dump($one['category']); if ($c = $this->syncGetProductCategorys($one['category'])){ //var_dump($c); $one['category'] = $c; } - $one['price'] = (float) $one['price']; $one['cost_price'] = (float) $one['cost_price']; $one['special_price'] = (float) $one['special_price']; $one['final_price'] = (float) $one['final_price']; - $saveStatus = Yii::$service->helper->ar->save($model, $one); $product_id = (string)$model->{$this->getPrimaryKey()}; - - // 自定义url部分 $originUrlKey = 'catalog/product/index'; $originUrl = $originUrlKey.'?'.$this->getPrimaryKey() .'='. $product_id; @@ -547,6 +510,7 @@ public function sync($one) protected function syncGetProductCategorys($mysqlCategorys) { if (empty($mysqlCategorys) || !is_array($mysqlCategorys)) { + return null; } @@ -565,6 +529,7 @@ protected function syncGetProductCategorys($mysqlCategorys) $cIds[] = (string)$one['_id']; } } + return $cIds; } @@ -667,15 +632,7 @@ protected function initSave(&$one) return false; } - //if (is_array($one['custom_option']) && !empty($one['custom_option'])) { - // $new_custom_option = []; - // foreach ($one['custom_option'] as $k=>$v) { - // $k = preg_replace('/[^A-Za-z0-9\-_]/', '', $k); - // $new_custom_option[$k] = $v; - // } - // $one['custom_option'] = $new_custom_option; - //} - + return true; } @@ -710,6 +667,7 @@ public function remove($ids) } } if (!$removeAll) { + return false; } } else { @@ -744,37 +702,37 @@ public function addAndDeleteProductCategory($category_id, $addCateProductIdArr, { // 在 addCategoryIdArr 查看哪些产品,分类id在product中已经存在, $idKey = $this->getPrimaryKey(); - //var_dump($addCateProductIdArr); if (is_array($addCateProductIdArr) && !empty($addCateProductIdArr) && $category_id) { $addCateProductIdArr = array_unique($addCateProductIdArr); foreach ($addCateProductIdArr as $product_id) { if (!$product_id) { + continue; } $product = $this->_productModel->findOne($product_id); if (!$product[$idKey]) { + continue; } $category = $product->category; $category = ($category && is_array($category)) ? $category : []; - //echo $category_id; if (!in_array($category_id, $category)) { - //echo $category_id; $category[] = $category_id; $product->category = $category; $product->save(); } } } - if (is_array($deleteCateProductIdArr) && !empty($deleteCateProductIdArr) && $category_id) { $deleteCateProductIdArr = array_unique($deleteCateProductIdArr); foreach ($deleteCateProductIdArr as $product_id) { if (!$product_id) { + continue; } $product = $this->_productModel->findOne($product_id); if (!$product[$idKey]) { + continue; } $category = $product->category; @@ -801,6 +759,7 @@ public function getProducts($filter) { $where = $filter['where']; if (empty($where)) { + return []; } $select = $filter['select']; @@ -833,6 +792,7 @@ public function getFrontCategoryProducts($filter){ public function getFrontCategoryProductsAll($filter){ $where = $filter['where']; if (empty($where)) { + return []; } if (!isset($where['status'])) { @@ -857,7 +817,6 @@ public function getFrontCategoryProductsAll($filter){ return $this->coll($filter); } - /** * 相同spu下面的所有sku,只显示一个,取score值最高的那个显示 *[ @@ -888,7 +847,6 @@ public function getFrontCategoryProductsGroupBySpu($filter) if (empty($where)) { return []; } - //var_dump($filter); if (!isset($where['status'])) { $where['status'] = $this->getEnableStatus(); } @@ -906,11 +864,7 @@ public function getFrontCategoryProductsGroupBySpu($filter) $group[$column] = ['$first' => '$'.$column]; } $group['product_id'] = ['$first' => '$product_id']; - - //var_dump($group); - //exit; $langCode = Yii::$service->store->currentLangCode; - $name_lang = Yii::$service->fecshoplang->getLangAttrName('name', $langCode); $default_name_lang = Yii::$service->fecshoplang->GetDefaultLangAttrName('name'); $project['name'] = [ @@ -940,8 +894,6 @@ public function getFrontCategoryProductsGroupBySpu($filter) '$limit' => Yii::$service->product->categoryAggregateMaxCount, ], ]; - //var_dump($pipelines);exit; - // ['cursor' => ['batchSize' => 2]] $product_data = $this->_productModel->getCollection()->aggregate($pipelines); $product_total_count = count($product_data); $pageOffset = ($pageNum - 1) * $numPerPage; @@ -962,6 +914,7 @@ public function getFrontCategoryProductsGroupBySpu($filter) public function getFrontCategoryFilter($filter_attr, $where) { if (empty($where)) { + return []; } if (!isset($where['status'])) { @@ -1062,7 +1015,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') } $currentDateTime = \fec\helpers\CDate::getCurrentDateTime(); $primaryVal = isset($one[$this->getPrimaryKey()]) ? $one[$this->getPrimaryKey()] : ''; - // 得到group spu attr $attr_group = $one['attr_group']; $groupSpuAttrs = Yii::$service->product->getGroupSpuAttr($attr_group); @@ -1072,7 +1024,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') $spuAttrArr[] = $groupSpuOne['name']; } } - if ($primaryVal) { $model = $this->_productModel->findOne($primaryVal); if (!$model) { @@ -1080,7 +1031,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') return false; } - //验证sku 是否重复 $product_one = $this->_productModel->find()->asArray()->where([ '<>', $this->getPrimaryKey(), (new \MongoDB\BSON\ObjectId($primaryVal)), @@ -1092,7 +1042,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') return false; } - // spu 下面的各个sku的spu属性不能相同 if (!empty($spuAttrArr)) { $product_mode = $this->_productModel->find()->asArray()->where([ @@ -1103,7 +1052,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') foreach ($spuAttrArr as $sar) { $product_mode->andWhere([$sar => $one[$sar]]); } - $product_one = $product_mode->one(); if ($product_one['sku']) { Yii::$service->helper->errors->add('product Spu of the same, Spu attributes cannot be the same'); @@ -1111,7 +1059,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') return false; } } - // 多语言属性,如果您有其他的多语言属性,可以自行二开添加。 $name =$model['name']; $meta_title = $model['meta_title']; @@ -1152,7 +1099,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') return false; } - if (!empty($spuAttrArr)) { $product_mode = $this->_productModel->find()->asArray()->where([ 'spu' => $one['spu'], @@ -1160,7 +1106,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') foreach ($spuAttrArr as $sar) { $product_mode->andWhere([$sar => $one[$sar]]); } - $product_one = $product_mode->one(); if ($product_one['sku']) { Yii::$service->helper->errors->add('product Spu of the same, Spu attributes cannot be the same'); @@ -1168,7 +1113,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') return false; } } - } $model->updated_at = time(); // 计算出来产品的最终价格。 @@ -1176,22 +1120,7 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') $one['score'] = (int) $one['score']; unset($one['_id']); unset($one['custom_option']); - /** - * 如果 $one['custom_option'] 不为空,则计算出来库存总数,填写到qty - */ - //if (is_array($one['custom_option']) && !empty($one['custom_option'])) { - // $custom_option_qty = 0; - // foreach ($one['custom_option'] as $co_one) { - // $custom_option_qty += $co_one['qty']; - // } - // $one['qty'] = $custom_option_qty; - //} - /** - * 保存产品 - */ - //var_dump($one);exit; $saveStatus = Yii::$service->helper->ar->save($model, $one); - // 自定义url部分 if ($originUrlKey) { $originUrl = $originUrlKey.'?'.$this->getPrimaryKey() .'='. $primaryVal; @@ -1201,7 +1130,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') $model->url_key = $urlKey; $model->save(); } - $product_id = $model->{$this->getPrimaryKey()}; /** * 更新产品库存。 diff --git a/services/product/ProductMysqldb.php b/services/product/ProductMysqldb.php index 7f8723ec9..265175fb1 100644 --- a/services/product/ProductMysqldb.php +++ b/services/product/ProductMysqldb.php @@ -35,17 +35,14 @@ class ProductMysqldb extends Service implements ProductInterface 'name', 'meta_title', 'tier_price', - 'meta_keywords', 'meta_description', 'image', 'description', 'short_description', - //'custom_option', 'remark', 'relation_sku', 'buy_also_buy_sku', - 'see_also_see_sku', 'attr_group_info', 'reviw_rate_star_average_lang', @@ -59,7 +56,6 @@ public function init() parent::init(); list($this->_productModelName, $this->_productModel) = \Yii::mapGet($this->_productModelName); list($this->_categoryProductModelName, $this->_categoryProductModel) = \Yii::mapGet($this->_categoryProductModelName); - } public function getPrimaryKey() @@ -78,6 +74,7 @@ public function serviceStorageName() public function getEnableStatus() { $model = $this->_productModel; + return $model::STATUS_ENABLE; } @@ -85,8 +82,10 @@ public function getByPrimaryKey($primaryKey = null) { if ($primaryKey) { $one = $this->_productModel->findOne($primaryKey); + return $this->unserializeData($one) ; } else { + return new $this->_productModelName(); } } @@ -143,6 +142,7 @@ public function getBySku($sku, $returnArr = true) } $primaryKey = $this->getPrimaryKey(); if (isset($product[$primaryKey]) && !empty($product[$primaryKey])) { + return $this->unserializeData($product) ; } } @@ -159,10 +159,12 @@ public function getBySpu($spu, $returnArr = true) { if ($spu) { if ($returnArr) { + return $this->_productModel->find()->asArray() ->where(['spu' => $spu]) ->all(); } else { + return $this->_productModel->find() ->where(['spu' => $spu]) ->all(); @@ -194,14 +196,13 @@ public function coll($filter = '') $filter['select'][] = $primaryKey; } } - //var_dump($filter['select']);exit; $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); - $coll = $query->all(); $arr = []; foreach ($coll as $one) { $arr[] = $this->unserializeData($one) ; } + return [ 'coll' => $arr, 'count'=> $query->limit(null)->offset(null)->count(), @@ -211,7 +212,6 @@ public function coll($filter = '') public function spuCollData($select, $spuAttrArr, $spu) { $select[] = 'attr_group_info'; - //var_dump($select);exit; $filter = [ 'select' => $select, 'where' => [ @@ -220,9 +220,7 @@ public function spuCollData($select, $spuAttrArr, $spu) 'asArray' => true, 'fetchAll' => true, ]; - $data = Yii::$service->product->coll($filter); - $coll = $data['coll']; $arr = []; foreach ($coll as $one) { @@ -264,7 +262,6 @@ public function apicoll() $arr[$spu_attr] = $spu_val; } } - } $collArr[] = $arr; } @@ -347,7 +344,6 @@ public function getCategoryProductIds($product_id_arr, $category_id) { $category_product_ids = $this->getProductIdsByCategoryId($category_id); $product_ids = array_intersect($category_product_ids, $product_id_arr); - $id_arr = []; if (is_array($product_ids) && !empty($product_ids)) { $query = $this->_productModel->find()->asArray(); @@ -412,11 +408,11 @@ public function checkSpuAttrUnique($spuAttrArr, $product_colls) public function save($one, $originUrlKey = 'catalog/product/index') { if (!$this->initSave($one)) { + return false; } $url_key = isset($one['url_key']) ? $one['url_key'] : ''; unset($one['url_key']); - $currentDateTime = \fec\helpers\CDate::getCurrentDateTime(); $primaryVal = isset($one[$this->getPrimaryKey()]) ? $one[$this->getPrimaryKey()] : ''; // 得到group spu attr @@ -428,7 +424,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') $spuAttrArr[$groupSpuOne['name']] = $one[$groupSpuOne['name']]; } } - if ($primaryVal) { if (!is_numeric($primaryVal)) { Yii::$service->helper->errors->add('Product {primaryKey} is not exist, current product services is mysql services, please fill in mysql product id', ['primaryKey'=>$this->getPrimaryKey()]); @@ -441,7 +436,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') return false; } - //验证sku 是否重复 $product_one = $this->_productModel->find()->asArray()->where([ '<>', $this->getPrimaryKey(), $primaryVal, @@ -460,21 +454,16 @@ public function save($one, $originUrlKey = 'catalog/product/index') ])->andWhere([ 'spu' => $one['spu'], ])->all(); - ///////////////// if (!$this->checkSpuAttrUnique($spuAttrArr, $product_colls)) { return false; } } } else { - $model = new $this->_productModelName(); $model->created_at = time(); $created_user_id = Yii::$app->user->identity->id; $model->created_user_id = $created_user_id ; - //$primaryVal = new \MongoDB\BSON\ObjectId(); - //$model->{$this->getPrimaryKey()} = $primaryVal; //验证sku 是否重复 - $product_one = $this->_productModel->find()->asArray()->where([ 'sku' => $one['sku'], ])->one(); @@ -484,39 +473,22 @@ public function save($one, $originUrlKey = 'catalog/product/index') return false; } - // spu 下面的各个sku的spu属性不能相同 if (!empty($spuAttrArr)) { $product_colls = $this->_productModel->find()->asArray()->where([ 'spu' => $one['spu'], ])->all(); - ///////////////// if (!$this->checkSpuAttrUnique($spuAttrArr, $product_colls)) { return false; } } - } - $model->updated_at = time(); // 计算出来产品的最终价格。 $one['final_price'] = Yii::$service->product->price->getFinalPrice($one['price'], $one['special_price'], $one['special_from'], $one['special_to']); $one['score'] = (int) $one['score']; unset($one['id']); unset($one['custom_option']); - /** - * 如果 $one['custom_option'] 不为空,则计算出来库存总数,填写到qty - */ - - //if (is_array($one['custom_option']) && !empty($one['custom_option'])) { - // $custom_option_qty = 0; - // foreach ($one['custom_option'] as $co_one) { - // $custom_option_qty += $co_one['qty']; - // } - // $one['qty'] = $custom_option_qty; - //} - - /** * 保存产品 */ @@ -525,21 +497,15 @@ public function save($one, $originUrlKey = 'catalog/product/index') $saveStatus = Yii::$service->helper->ar->save($model, $one); $product_id = $model->{$this->getPrimaryKey()}; // 保存分类 - $this->updateProductCategory($one['category'], $product_id); // 自定义url部分 if ($originUrlKey) { $originUrl = $originUrlKey.'?'.$this->getPrimaryKey() .'='. $product_id; $originUrlKey = $url_key; - $urlKey = Yii::$service->url->saveRewriteUrlKeyByStr($defaultLangTitle, $originUrl, $originUrlKey); $model->url_key = $urlKey; - $model->save(); } - - - /** * 更新产品库存。 */ @@ -547,7 +513,6 @@ public function save($one, $originUrlKey = 'catalog/product/index') /** * 更新产品信息到搜索表。 */ - Yii::$service->search->syncProductInfo([$product_id]); return $model; @@ -561,6 +526,7 @@ public function save($one, $originUrlKey = 'catalog/product/index') public function sync($one) { if (!$this->initSave($one)) { + return false; } $url_key = isset($one['url_key']) ? $one['url_key'] : ''; @@ -583,17 +549,6 @@ public function sync($one) $one['score'] = (int) $one['score']; unset($one['_id']); unset($one['custom_option']); - /** - * 如果 $one['custom_option'] 不为空,则计算出来库存总数,填写到qty - */ - //if (is_array($one['custom_option']) && !empty($one['custom_option'])) { - // $custom_option_qty = 0; - // foreach ($one['custom_option'] as $co_one) { - // $custom_option_qty += $co_one['qty']; - // } - // $one['qty'] = $custom_option_qty; - //} - /** * 保存产品 */ @@ -601,7 +556,6 @@ public function sync($one) $saveStatus = Yii::$service->helper->ar->save($model, $one); $product_id = $model->{$this->getPrimaryKey()}; // 保存分类 - $this->syncProductCategory($one['category'], $product_id); // 自定义url部分 $originUrl = 'catalog/product/index' . '?' . $this->getPrimaryKey() .'='. $product_id; @@ -629,6 +583,7 @@ public function sync($one) protected function syncProductCategory($category_ids, $product_id) { if (!is_array($category_ids)) { + return ; } Yii::$service->category->changeToMysqlStorage(); @@ -672,8 +627,8 @@ protected function serializeSaveData($one) unset($one[$k]); } } - $one['attr_group_info'] = serialize($groupArr); + return $one; } @@ -682,6 +637,7 @@ protected function unserializeData($one, $withCategory = false) { if (!is_array($one) && !is_object($one)) { + return $one; } foreach ($one as $k => $v) { @@ -698,6 +654,7 @@ protected function unserializeData($one, $withCategory = false) public function getCategoryIdsByProductId($product_id) { if (empty($product_id)) { + return []; } $coll = $this->_categoryProductModel->find() @@ -720,6 +677,7 @@ public function getCategoryIdsByProductId($product_id) public function getCategoryIdsByProductIds($product_ids) { if (empty($product_ids) || !is_array($product_ids)) { + return []; } $coll = $this->_categoryProductModel->find() @@ -742,6 +700,7 @@ public function getCategoryIdsByProductIds($product_ids) public function getCategorysByProductIds($product_ids) { if (empty($product_ids) || !is_array($product_ids)) { + return []; } $coll = $this->_categoryProductModel->find() @@ -818,15 +777,7 @@ protected function initSave(&$one) return false; } - //if (is_array($one['custom_option']) && !empty($one['custom_option'])) { - // $new_custom_option = []; - // foreach ($one['custom_option'] as $k=>$v) { - // $k = preg_replace('/[^A-Za-z0-9\-_]/', '', $k); - // $new_custom_option[$k] = $v; - // } - // $one['custom_option'] = $new_custom_option; - //} - + return true; } @@ -854,7 +805,6 @@ public function remove($ids) Yii::$service->search->removeByProductId($id); Yii::$service->product->stock->removeProductStock($id); $model->delete(); - //$this->removeChildCate($id); } else { Yii::$service->helper->errors->add('Product Remove Errors:ID:{id} is not exist', ['id'=>$id]); $removeAll = 0; @@ -876,7 +826,6 @@ public function remove($ids) Yii::$service->product->stock->removeProductStock($id); $model->delete(); $this->removeCategoryProductRelationByProductId($id); - //$this->removeChildCate($id); } else { Yii::$service->helper->errors->add('Product Remove Errors:ID:{id} is not exist.', ['id'=>$id]); @@ -914,7 +863,6 @@ public function updateProductCategory($category_ids, $product_id) */ public function addAndDeleteProductCategory($category_id, $addCateProductIdArr, $deleteCateProductIdArr) { - // 删除 if (is_array($deleteCateProductIdArr) && !empty($deleteCateProductIdArr) && $category_id) { $this->_categoryProductModel->deleteAll([ @@ -923,7 +871,6 @@ public function addAndDeleteProductCategory($category_id, $addCateProductIdArr, ['in','product_id',$deleteCateProductIdArr] ]); } - // 添加 if (is_array($addCateProductIdArr) && !empty($addCateProductIdArr) && $category_id) { foreach ($addCateProductIdArr as $product_id) { @@ -965,7 +912,6 @@ public function getProducts($filter) if (is_array($select) && !empty($select)) { $query->select($select); } - $coll = $query->all(); $arr = []; foreach ($coll as $one) { @@ -1020,7 +966,6 @@ public function getFrontCategoryProductsAll($filter){ } else { $whereArr[] = [$k =>$v]; } - } $where = $whereArr; } @@ -1028,7 +973,6 @@ public function getFrontCategoryProductsAll($filter){ $pageNum = $filter['pageNum']; $numPerPage = $filter['numPerPage']; $select = $filter['select']; - $filter = [ 'numPerPage' => $numPerPage, 'pageNum' => $pageNum, @@ -1040,7 +984,6 @@ public function getFrontCategoryProductsAll($filter){ return $this->coll($filter); } - /** * 相同spu下面的所有sku,只显示一个,取score值最高的那个显示 *[ @@ -1071,7 +1014,6 @@ public function getFrontCategoryProductsGroupBySpu($filter) $pageNum = $filter['pageNum']; $numPerPage = $filter['numPerPage']; $select = $filter['select']; - $where = $filter['where']; if (empty($where)) { return []; @@ -1101,7 +1043,6 @@ public function getFrontCategoryProductsGroupBySpu($filter) } else { $whereArr[] = [$k =>$v]; } - } $where = $whereArr; } @@ -1120,7 +1061,6 @@ public function getFrontCategoryProductsGroupBySpu($filter) $subQuery2 = (new Query()) ->from(['product2' => $subQuery]) ->groupBy('spu'); - // 进行查询coll $products = (new Query()) //->select($field) ->from(['product' => $subQuery2]) // 在这里使用了子查询 @@ -1128,12 +1068,12 @@ public function getFrontCategoryProductsGroupBySpu($filter) ->offset(($pageNum -1) * $numPerPage) ->limit($numPerPage) ->createCommand() - //->getRawSql(); // ->queryAll(); foreach ($products as $k => $product) { $products[$k]['name'] = unserialize($product['name']); $products[$k]['image'] = unserialize($product['image']); } + return [ 'coll' => $products, 'count' => $product_total_count, @@ -1155,15 +1095,16 @@ public function getFrontCategoryProductsGroupBySpu($filter) public function getFrontCategoryFilter($filter_attr, $where) { if (empty($where)) { + return []; } if (!isset($where['status'])) { $where['status'] = $this->getEnableStatus(); } if (!$this->_productModel->hasAttribute($filter_attr)) { + return []; } - // where条件处理 if ($categoryId = $where['category']) { $productIds = $this->getProductIdsByCategoryId($categoryId); @@ -1178,7 +1119,6 @@ public function getFrontCategoryFilter($filter_attr, $where) } $where = $whereArr; } - // 总数 $filter_data = $this->_productModel->find() ->select($filter_attr.' as _id , COUNT(*) as count') @@ -1189,9 +1129,6 @@ public function getFrontCategoryFilter($filter_attr, $where) return $filter_data; } - - - /** * @param $spu | String * @param $avag_rate | Int ,平均评星 @@ -1217,14 +1154,11 @@ public function updateProductReviewInfo($spu, $avag_rate, $count, $lang_code, $a $one['reviw_rate_star_average'] = $avag_rate; $one['review_count'] = $count; $a = $one['reviw_rate_star_average_lang']; - //$a[$review_star_lang] = $avag_lang_rate; $b = $one['review_count_lang']; - //$b[$review_count_lang] = $lang_count; $one['reviw_rate_star_average_lang'] = $a; $one['review_count_lang'] = $b; $one['reviw_rate_star_info'] = serialize($rate_total_arr); $c = $one['reviw_rate_star_info_lang']; - //$c[$reviw_rate_star_info_lang] = $rate_lang_total_arr; $one['reviw_rate_star_info_lang'] = $c; $one->save(); } @@ -1245,13 +1179,11 @@ public function updateAllScoreToZero(){ return $this->_productModel->getCollection()->update([], ['score' => 0]); } - public function removeCategoryProductRelationByProductId($product_id) { return $this->_categoryProductModel->deleteAll(['product_id' => $product_id]); } - /** * 保存Excel上传文件的数据 */ @@ -1305,7 +1237,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') ])->andWhere([ 'spu' => $one['spu'], ])->all(); - ///////////////// if (!$this->checkSpuAttrUnique($spuAttrArr, $product_colls)) { return false; } @@ -1317,7 +1248,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') $meta_description = $model['meta_description']; $short_description = $model['short_description']; $description = $model['description']; - //var_dump($description); if (is_array($one['name']) && !empty($one['name'])) { $one['name'] = array_merge((is_array($name) ? $name : []), $one['name']); } @@ -1341,26 +1271,20 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') $model->created_at = time(); $created_user_id = Yii::$app->user->identity->id; $model->created_user_id = $created_user_id ; - //$primaryVal = new \MongoDB\BSON\ObjectId(); - //$model->{$this->getPrimaryKey()} = $primaryVal; //验证sku 是否重复 - $product_one = $this->_productModel->find()->asArray()->where([ 'sku' => $one['sku'], ])->one(); - if ($product_one['sku']) { Yii::$service->helper->errors->add('Product Sku is exist,please use other sku'); return false; } - // spu 下面的各个sku的spu属性不能相同 if (!empty($spuAttrArr)) { $product_colls = $this->_productModel->find()->asArray()->where([ 'spu' => $one['spu'], ])->all(); - ///////////////// if (!$this->checkSpuAttrUnique($spuAttrArr, $product_colls)) { return false; } @@ -1380,7 +1304,6 @@ public function excelSave($one, $originUrlKey = 'catalog/product/index') $saveStatus = Yii::$service->helper->ar->save($model, $one); $product_id = $model->{$this->getPrimaryKey()}; // 保存分类 - $this->updateProductCategory($one['category'], $product_id); // 自定义url部分 if ($originUrlKey) { diff --git a/services/product/Review.php b/services/product/Review.php index 20337fa4d..e90be910a 100644 --- a/services/product/Review.php +++ b/services/product/Review.php @@ -32,13 +32,11 @@ */ class Review extends Service { - /** * $storagePrex , $storage , $storagePath 为找到当前的storage而设置的配置参数 * 可以在配置中更改,更改后,就会通过容器注入的方式修改相应的配置值 */ public $storage; // = 'ReviewMysqldb'; // ReviewMysqldb | ReviewMongodb 当前的storage,如果在config中配置,那么在初始化的时候会被注入修改 - /** * 设置storage的path路径, * 如果不设置,则系统使用默认路径 @@ -65,7 +63,6 @@ public function init() $reviewOnlyOrderedProduct = Yii::$app->store->get($appName.'_catalog','review_OnlyOrderedProduct'); $this->reviewOnlyOrderedProduct = ($reviewOnlyOrderedProduct == Yii::$app->store->enable) ? true : false; $this->reviewMonth = Yii::$app->store->get($appName.'_catalog','review_MonthLimit'); - //$this->reviewOnlyOrderedProduct = ($reviewOnlyOrderedProduct == Yii::$app->store->enable) ? true : false; // 从数据库配置中得到值, 设置成当前service存储,是Mysqldb 还是 Mongodb $config = Yii::$app->store->get('service_db', 'product_review'); $this->storage = 'ReviewMysqldb'; @@ -74,8 +71,8 @@ public function init() } $currentService = $this->getStorageService($this); $this->_review = new $currentService(); - //var_dump([$this->filterByLang , $this->reviewOnlyOrderedProduct, $this->reviewMonth]); } + // 动态更改为mongodb model public function changeToMongoStorage() { @@ -106,6 +103,7 @@ public function activeStatus() { return $this->_review->activeStatus(); } + public function refuseStatus() { return $this->_review->refuseStatus(); @@ -115,6 +113,7 @@ public function getPrimaryKey() { return $this->_review->getPrimaryKey(); } + /** * @param $spu | String. * 通过spu找到评论总数。 @@ -123,6 +122,7 @@ public function getCountBySpu($spu) { return $this->_review->getCountBySpu($spu); } + /** * example filter: * [ @@ -140,6 +140,7 @@ public function getListBySpu($filter) { return $this->_review->getListBySpu($filter); } + /** * @param $review_data | Array * @@ -149,10 +150,12 @@ public function addReview($review_data) { return $this->_review->addReview($review_data); } + public function updateReview($review_data) { return $this->_review->updateReview($review_data); } + /** * 查看review 的列表 */ @@ -160,16 +163,17 @@ public function actionList($filter) { return $this->_review->list($filter); } + public function getByReviewId($_id) { return $this->_review->getByReviewId($_id); } + public function getByPrimaryKey($primaryKey) { return $this->_review->getByPrimaryKey($primaryKey); } - public function coll($filter = '') { return $this->_review->coll($filter); @@ -209,6 +213,4 @@ public function getReviewsByUserId($filter) } - - } diff --git a/services/product/Stock.php b/services/product/Stock.php index efcfb473b..7ecbb67a2 100644 --- a/services/product/Stock.php +++ b/services/product/Stock.php @@ -10,9 +10,6 @@ namespace fecshop\services\product; -//use fecshop\models\mongodb\Product; -//use fecshop\models\mysqldb\product\ProductFlatQty; -//use fecshop\models\mysqldb\product\ProductCustomOptionQty; use fecshop\services\Service; use Yii; @@ -74,6 +71,7 @@ public function getQtyByProductIds($productIds) { if (!is_array($productIds)) { Yii::$service->helper->errors->add('ProductIds must be Array'); + return false; } $data = $this->_flatQtyModel->find()->asArray()->where([ @@ -83,6 +81,7 @@ public function getQtyByProductIds($productIds) foreach ($data as $one) { $arr[$one['product_id']] = $one['qty']; } + return $arr; } @@ -108,7 +107,6 @@ public function saveProductStock($product_id, $one) if (!isset($one['qty'])) { Yii::$service->helper->errors->add('save product qty error: product qty is empty'); } - // 保存自定义部分的qty if (is_array($one['custom_option']) && !empty($one['custom_option'])) { $custom_option_qty = 0; @@ -135,7 +133,6 @@ public function saveProductStock($product_id, $one) // 如果是custom option,主库存 = 各个custom option 的库存的相加和 $one['qty'] = $custom_option_qty; $delete_sku_arr = array_diff($co_sku_arr, $product_sku_arr); - //var_dump($delete_sku_arr); // 删除掉产品中不存在customOptionSku对应的库存、 if (!empty($delete_sku_arr) && is_array($delete_sku_arr)) { $this->_COQtyModel->deleteAll([ @@ -155,6 +152,7 @@ public function saveProductStock($product_id, $one) } $productFlatQty->qty = $one['qty']; $productFlatQty->save(); + return true; } @@ -170,6 +168,7 @@ public function removeProductStock($product_id) // 保存产品flat qty $this->_flatQtyModel->deleteAll(['product_id' => $product_id]); $this->_COQtyModel->deleteAll(['product_id' => $product_id]); + return true; } @@ -196,7 +195,7 @@ public function removeProductStock($product_id) * **注意**:在调用该函数的时候必须使用事务,在返回false的时候要回滚。 * **注意**:在调用该函数的时候必须使用事务,在返回false的时候要回滚。 */ - protected function actionDeduct($items = []) + public function deduct($items = []) { if (!$items) { // 如果 $items 为空,则去购物车取数据。 @@ -206,6 +205,7 @@ protected function actionDeduct($items = []) // 如果items为空,则返回 if (!is_array($items) || empty($items)) { Yii::$service->helper->errors->add('cart products is empty'); + return false; } // 查看产品的状态,上下架状态,以及产品库存检查是否够用。 @@ -217,10 +217,12 @@ protected function actionDeduct($items = []) // 购物车中的产品已经被删除,则会查询不到 if (!$product['sku']) { Yii::$service->helper->errors->add('product: [ {product_id} ] is not exist', ['product_id' => $product_id]); + return false; } $status = $this->productIsInStock($product, $sale_qty, $custom_option_sku); if (!$status) { + return false; } } @@ -229,9 +231,9 @@ protected function actionDeduct($items = []) * 如果满足上架状态 && 零库存为1,则直接返回。 */ if ($this->zeroInventory) { + return true; // 零库存模式 不会更新产品库存。 } - // 开始扣除库存。 foreach ($items as $k=>$item) { $product_id = $item['product_id']; @@ -246,6 +248,7 @@ protected function actionDeduct($items = []) ); if (empty($updateColumns)) {// 上面更新sql返回的更新行数如果为0,则说明更新失败,产品不存在,或者产品库存不够 Yii::$service->helper->errors->add('product: [ {product_name} ] is stock out', ['product_name' => $product_name]); + return false; } // 对于custom option(淘宝模式)的库存扣除 @@ -263,6 +266,7 @@ protected function actionDeduct($items = []) ); if (empty($updateColumns)) {// 上面更新sql返回的更新行数如果为0,则说明更新失败,产品不存在,或者产品库存不够 Yii::$service->helper->errors->add('product: [ {product_name} ] is stock out', ['product_name' => $product_name]); + return false; } } @@ -272,7 +276,6 @@ protected function actionDeduct($items = []) return true; } - /** * @var array $items * example: @@ -296,15 +299,13 @@ protected function actionDeduct($items = []) * **注意**:在调用该函数的时候必须使用事务,在返回false的时候要回滚。 * **注意**:在调用该函数的时候必须使用事务,在返回false的时候要回滚。 */ - protected function actionUpdatebybase($items = []) + public function updatebybase($items = []) { if (empty($items) || !is_array($items)) { Yii::$service->helper->errors->add('param items is not array or is empty'); return false; } - - // 查看产品的状态,上下架状态,以及产品库存检查是否够用。 foreach ($items as $k=>$item) { $sku = $item['sku']; @@ -324,8 +325,6 @@ protected function actionUpdatebybase($items = []) } $primaryKey = Yii::$service->product->getPrimaryKey(); $items[$k]['product_id'] = (string)$product[$primaryKey]; - - } /** @@ -345,12 +344,10 @@ protected function actionUpdatebybase($items = []) $custom_option_sku = $item['custom_option_sku']; if ($product_id && $sale_qty) { // 应对高并发库存超卖的控制,扣除库存的时候,加上qty个数的查询,不满足查询条件则不扣除库存 - $updateColumns = $this->_flatQtyModel->updateAllCounters( ['qty' => $sale_qty], ['and', ['product_id' => $product_id], ['>=', 'qty', 0 - $sale_qty]] ); - if (empty($updateColumns)) {// 上面更新sql返回的更新行数如果为0,则说明更新失败,产品不存在,或者产品库存不够 Yii::$service->helper->errors->add('product: [ {sku} ] is stock out', ['sku' => $sku]); @@ -397,9 +394,10 @@ protected function actionUpdatebybase($items = []) * @return bool * 返还产品库存。如果在返还过程中产品不存在,也不会返回false */ - protected function actionReturnQty($product_items) + public function returnQty($product_items) { if ($this->zeroInventory) { + return true; // 零库存模式不扣产品库存,也不需要返还库存。 } // 开始扣除库存。 @@ -429,7 +427,7 @@ protected function actionReturnQty($product_items) * @return bool * 查看产品库存 */ - protected function actionProductIsInStock($product, $sale_qty, $custom_option_sku, $checkDbQty = true) + public function productIsInStock($product, $sale_qty, $custom_option_sku, $checkDbQty = true) { $productPrimaryKey = Yii::$service->product->getPrimaryKey(); $is_in_stock = $product['is_in_stock']; @@ -479,7 +477,6 @@ protected function actionProductIsInStock($product, $sale_qty, $custom_option_sk $productFlatQty = $this->_flatQtyModel->find()->where([ 'product_id' => $product_id ])->one(); - if (!$productFlatQty['qty']) { $productName = Yii::$service->store->getStoreAttrVal($product['name'], 'name'); Yii::$service->helper->errors->add( @@ -494,6 +491,7 @@ protected function actionProductIsInStock($product, $sale_qty, $custom_option_sk 'Product Id: {product_id}, Product inventory is less than [{sale_qty}]', ['product_id' => $product[$productPrimaryKey], 'sale_qty' => $sale_qty] ); + return false; } } @@ -501,7 +499,6 @@ protected function actionProductIsInStock($product, $sale_qty, $custom_option_sk return true; } - /** * @param $items | Array , example: * [ @@ -541,7 +538,7 @@ protected function actionProductIsInStock($product, $sale_qty, $custom_option_sk * 购物车没有产品返回null * */ - protected function actionCheckItemsQty() + public function checkItemsQty() { $cartInfo = Yii::$service->cart->getCartInfo(true); $items = isset($cartInfo['products']) ? $cartInfo['products'] : ''; @@ -584,9 +581,7 @@ protected function actionCheckItemsQty() $productM = $this->_flatQtyModel->find()->where([ 'product_id' => $product_id ])->one(); - if ($productM['qty']) { - //echo $productM['qty'].'####'.$sale_qty.'
'; if ($productM['qty'] < $sale_qty) { $outStockProducts[] = [ 'product_id' => $product_id, @@ -630,11 +625,13 @@ protected function actionCheckItemsQty() } } if (empty($outStockProducts)) { + return [ 'stockStatus' => 1, 'outStockProducts' => '', ]; } else { + return [ 'stockStatus' => 2, 'outStockProducts' => $outStockProducts, @@ -642,6 +639,7 @@ protected function actionCheckItemsQty() } } else { Yii::$service->helper->errors->add('cart products is empty'); + return null; } } @@ -653,7 +651,7 @@ protected function actionCheckItemsQty() * @return bool * 检查产品是否是上架上台 */ - protected function actionCheckOnShelfStatus($is_in_stock) + public function checkOnShelfStatus($is_in_stock) { if ($is_in_stock == 1) { @@ -674,8 +672,10 @@ public function getProductFlatQty($product_id) 'product_id' => $product_id ])->one(); if (isset($productFlatQty['qty'])) { + return $productFlatQty['qty'] ? $productFlatQty['qty'] : 0; } else { + return 0; } } @@ -719,6 +719,7 @@ public function getProductCustomOptionSkuArr($product_id) $sku_arr[] = $one['custom_option_sku']; } } + return $sku_arr; } @@ -734,9 +735,12 @@ public function getProductCustomOptionSkuQty($product_id, $custom_option_sku) 'custom_option_sku' => $custom_option_sku ])->one(); if (isset($productCustomOptionQty['qty'])) { + return $productCustomOptionQty['qty']; } else { + return 0; } } + } diff --git a/services/product/attr/AttrMysqldb.php b/services/product/attr/AttrMysqldb.php index 8e1b1c6a7..af103aaf6 100644 --- a/services/product/attr/AttrMysqldb.php +++ b/services/product/attr/AttrMysqldb.php @@ -27,8 +27,6 @@ class AttrMysqldb extends Service implements AttrInterface protected $_attrModel; - - public function init() { parent::init(); @@ -40,8 +38,6 @@ public function getPrimaryKey() return 'id'; } - - /** * 得到分类激活状态的值 */ @@ -51,20 +47,18 @@ public function getEnableStatus() return $model::STATUS_ENABLE; } - public function getByPrimaryKey($primaryKey = null) { if ($primaryKey) { $one = $this->_attrModel->findOne($primaryKey); return $one; - //return $this->unserializeData($one) ; } else { + return new $this->_attrModel(); } } - /* * example filter: * [ @@ -85,10 +79,7 @@ public function coll($filter = '') $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); $coll = $query->all(); - //$arr = []; - //foreach ($coll as $one) { - // $arr[] = $this->unserializeData($one) ; - //} + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -143,7 +134,6 @@ public function remove($ids) public function getActiveAllColl() { - // attribute Group $filter = [ 'where' => [ ['status' => $this->getEnableStatus()] @@ -153,7 +143,6 @@ public function getActiveAllColl() ]; $query = $this->_attrModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); - $coll = $query->all(); if (is_array($coll)) { foreach ($coll as $k => $one) { @@ -161,11 +150,11 @@ public function getActiveAllColl() $coll[$k]['display_data'] = unserialize($one['display_data']); } } + return $coll; } return null; - } } diff --git a/services/product/attrgroup/AttrGroupMysqldb.php b/services/product/attrgroup/AttrGroupMysqldb.php index d52deb1ad..dcf8bc2e4 100644 --- a/services/product/attrgroup/AttrGroupMysqldb.php +++ b/services/product/attrgroup/AttrGroupMysqldb.php @@ -27,8 +27,6 @@ class AttrGroupMysqldb extends Service implements AttrGroupInterface protected $_attrGroupModel; - - public function init() { parent::init(); @@ -40,14 +38,13 @@ public function getPrimaryKey() return 'id'; } - - /** * 得到分类激活状态的值 */ public function getEnableStatus() { $model = $this->_attrGroupModel; + return $model::STATUS_ENABLE; } @@ -55,13 +52,14 @@ public function getByPrimaryKey($primaryKey = null) { if ($primaryKey) { $one = $this->_attrGroupModel->findOne($primaryKey); + return $one; } else { + return new $this->_attrGroupModel(); } } - /* * example filter: * [ @@ -80,7 +78,6 @@ public function coll($filter = '') { $query = $this->_attrGroupModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); - $coll = $query->all(); //$arr = []; //foreach ($coll as $one) { @@ -150,7 +147,6 @@ public function getActiveAllColl() ]; $query = $this->_attrGroupModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); - $coll = $query->all(); if (is_array($coll)) { foreach ($coll as $k => $groupOne) { @@ -159,6 +155,7 @@ public function getActiveAllColl() $coll[$k]['attr_ids'] = $attr_ids; } } + return $coll; } diff --git a/services/product/favorite/FavoriteMongodb.php b/services/product/favorite/FavoriteMongodb.php index e09d0d755..ae4b3f323 100644 --- a/services/product/favorite/FavoriteMongodb.php +++ b/services/product/favorite/FavoriteMongodb.php @@ -31,17 +31,19 @@ public function init() list($this->_favoriteModelName, $this->_favoriteModel) = \Yii::mapGet($this->_favoriteModelName); } - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return '_id'; } - protected function actionGetByPrimaryKey($val) + public function getByPrimaryKey($val) { $one = $this->_favoriteModel->findOne($val); if ($one[$this->getPrimaryKey()]) { + return $one; } else { + return new $this->_favoriteModelName(); } } @@ -51,7 +53,7 @@ protected function actionGetByPrimaryKey($val) * @param $user_id | Int ,用户id * @return $this->_favoriteModel ,如果用户在该产品收藏,则返回相应model。 */ - protected function actionGetByProductIdAndUserId($product_id, $user_id = '') + public function getByProductIdAndUserId($product_id, $user_id = '') { if (!$user_id) { $identity = Yii::$app->user->identity; @@ -63,6 +65,7 @@ protected function actionGetByProductIdAndUserId($product_id, $user_id = '') 'user_id' => $user_id, ]); if ($one[$this->getPrimaryKey()]) { + return $one; } } @@ -73,7 +76,7 @@ protected function actionGetByProductIdAndUserId($product_id, $user_id = '') * @param $user_id | Int ,用户id * @return boolean,用户收藏该产品时,执行的操作。 */ - protected function actionAdd($product_id, $user_id) + public function add($product_id, $user_id) { $user_id = (int) $user_id; $productPrimaryKey = Yii::$service->product->getPrimaryKey(); @@ -84,7 +87,6 @@ protected function actionAdd($product_id, $user_id) return; } - //echo $product_id;exit; $favoritePrimaryKey = Yii::$service->product->favorite->getPrimaryKey(); $one = $this->_favoriteModel->findOne([ 'product_id' => $product_id, @@ -154,7 +156,7 @@ protected function updateUserFavoriteCount($user_id = '') * 'asArray' => true, * ] */ - protected function actionList($filter) + public function list($filter) { $query = $this->_favoriteModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); @@ -165,7 +167,7 @@ protected function actionList($filter) ]; } - protected function actionColl($filter) + public function coll($filter) { return $this->list($filter); } @@ -178,9 +180,7 @@ public function removeByProductIdAndUserId($product_id, $user_id) { $identity = Yii::$app->user->identity; $user_id = $identity['id']; - $one = $this->_favoriteModel->findOne([ - //'_id' => new \MongoDB\BSON\ObjectId($favorite_id), 'user_id' => $user_id, 'product_id' => $product_id, ]); @@ -198,11 +198,10 @@ public function removeByProductIdAndUserId($product_id, $user_id) * @param $favorite_id | string * 通过id删除favorite */ - protected function actionCurrentUserRemove($favorite_id) + public function currentUserRemove($favorite_id) { $identity = Yii::$app->user->identity; $user_id = $identity['id']; - $one = $this->_favoriteModel->findOne([ '_id' => new \MongoDB\BSON\ObjectId($favorite_id), 'user_id' => $user_id, diff --git a/services/product/favorite/FavoriteMysqldb.php b/services/product/favorite/FavoriteMysqldb.php index da6eefdc8..798f9336b 100644 --- a/services/product/favorite/FavoriteMysqldb.php +++ b/services/product/favorite/FavoriteMysqldb.php @@ -31,17 +31,19 @@ public function init() list($this->_favoriteModelName, $this->_favoriteModel) = \Yii::mapGet($this->_favoriteModelName); } - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return 'id'; } - protected function actionGetByPrimaryKey($val) + public function getByPrimaryKey($val) { $one = $this->_favoriteModel->findOne($val); if ($one[$this->getPrimaryKey()]) { + return $one; } else { + return new $this->_favoriteModelName(); } } @@ -51,7 +53,7 @@ protected function actionGetByPrimaryKey($val) * @param $user_id | Int ,用户id * @return $this->_favoriteModel ,如果用户在该产品收藏,则返回相应model。 */ - protected function actionGetByProductIdAndUserId($product_id, $user_id = '') + public function getByProductIdAndUserId($product_id, $user_id = '') { if (!$user_id) { $identity = Yii::$app->user->identity; @@ -63,6 +65,7 @@ protected function actionGetByProductIdAndUserId($product_id, $user_id = '') 'user_id' => $user_id, ]); if ($one[$this->getPrimaryKey()]) { + return $one; } } @@ -73,7 +76,7 @@ protected function actionGetByProductIdAndUserId($product_id, $user_id = '') * @param $user_id | Int ,用户id * @return boolean,用户收藏该产品时,执行的操作。 */ - protected function actionAdd($product_id, $user_id) + public function add($product_id, $user_id) { $user_id = (int) $user_id; $productPrimaryKey = Yii::$service->product->getPrimaryKey(); @@ -84,7 +87,6 @@ protected function actionAdd($product_id, $user_id) return; } - //echo $product_id;exit; $favoritePrimaryKey = Yii::$service->product->favorite->getPrimaryKey(); $one = $this->_favoriteModel->findOne([ 'product_id' => $product_id, @@ -154,7 +156,7 @@ protected function updateUserFavoriteCount($user_id = '') * 'asArray' => true, * ] */ - protected function actionList($filter) + public function list($filter) { $query = $this->_favoriteModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); @@ -165,7 +167,7 @@ protected function actionList($filter) ]; } - protected function actionColl($filter) + public function coll($filter) { return $this->list($filter); } @@ -180,7 +182,6 @@ public function removeByProductIdAndUserId($product_id, $user_id) $user_id = $identity['id']; $favoritePrimaryKey = $this->getPrimaryKey(); $one = $this->_favoriteModel->findOne([ - //'_id' => new \MongoDB\BSON\ObjectId($favorite_id), 'user_id' => $user_id, 'product_id' => $product_id, ]); @@ -198,7 +199,7 @@ public function removeByProductIdAndUserId($product_id, $user_id) * @param $favorite_id | string * 通过id删除favorite */ - protected function actionCurrentUserRemove($favorite_id) + public function currentUserRemove($favorite_id) { $identity = Yii::$app->user->identity; $user_id = $identity['id']; diff --git a/services/product/review/ReviewMongodb.php b/services/product/review/ReviewMongodb.php index 82b02de57..9beb29c7c 100644 --- a/services/product/review/ReviewMongodb.php +++ b/services/product/review/ReviewMongodb.php @@ -32,7 +32,6 @@ class ReviewMongodb extends Service implements ReviewInterface public function init() { parent::init(); - //$this->_viewService = Yii::$service->product->review; list($this->_reviewModelName, $this->_reviewModel) = \Yii::mapGet($this->_reviewModelName); } @@ -52,13 +51,15 @@ public function getReviewService() public function isReviewRole($product_id) { if (!$this->getReviewService()->reviewOnlyOrderedProduct) { + return true; } $itmes = Yii::$service->order->item->getByProductIdAndCustomerId($product_id, $this->getReviewService()->reviewMonth); - //var_dump($itmes);exit; if ($itmes) { + return true; } else { + return false; } } @@ -69,6 +70,7 @@ public function isReviewRole($product_id) public function noActiveStatus() { $model = $this->_reviewModel; + return $model::NOACTIVE_STATUS; } @@ -78,6 +80,7 @@ public function noActiveStatus() public function activeStatus() { $model = $this->_reviewModel; + return $model::ACTIVE_STATUS; } @@ -87,6 +90,7 @@ public function activeStatus() public function refuseStatus() { $model = $this->_reviewModel; + return $model::REFUSE_STATUS; } @@ -101,12 +105,11 @@ public function getPrimaryKey() * @param $spu | String. * 通过spu找到评论总数。 */ - protected function actionGetCountBySpu($spu) + public function getCountBySpu($spu) { $where = [ 'product_spu' => $spu, ]; - if ($this->getReviewService()->filterByLang && ($currentLangCode = Yii::$service->store->currentLangCode)) { $where['lang_code'] = $currentLangCode; } @@ -128,7 +131,7 @@ protected function actionGetCountBySpu($spu) * ] * 通过spu找到评论listing. */ - protected function actionGetListBySpu($filter) + public function getListBySpu($filter) { if ($this->getReviewService()->filterByLang && ($currentLangCode = Yii::$service->store->currentLangCode)) { $filter['where'][] = ['lang_code' => $currentLangCode]; @@ -147,7 +150,7 @@ protected function actionGetListBySpu($filter) * * 增加评论 前台增加评论调用的函数。 */ - protected function actionAddReview($review_data) + public function addReview($review_data) { //$this->initReviewAttr($review_data); $model = new $this->_reviewModelName(); @@ -156,7 +159,6 @@ protected function actionAddReview($review_data) } $model = $this->_reviewModel; $review_data['status'] = $model::NOACTIVE_STATUS; - $review_data['store'] = Yii::$service->store->currentStore; $review_data['lang_code'] = Yii::$service->store->currentLangCode; $review_data['review_date'] = time(); @@ -165,7 +167,6 @@ protected function actionAddReview($review_data) $user_id = $identity['id']; $review_data['user_id'] = $user_id; } - $review_data['ip'] = \fec\helpers\CFunc::get_real_ip(); $saveStatus = Yii::$service->helper->ar->save($model, $review_data); @@ -176,7 +177,7 @@ protected function actionAddReview($review_data) * @param $review_data | Array * 保存评论 */ - protected function actionUpdateReview($review_data) + public function updateReview($review_data) { //$this->initReviewAttr($review_data); $model = $this->_reviewModel->findOne([$this->getPrimaryKey()=> $review_data[$this->getPrimaryKey()]]); @@ -201,7 +202,7 @@ protected function actionUpdateReview($review_data) * ] * 查看review 的列表 */ - protected function actionList($filter) + public function list($filter) { $query = $this->_reviewModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); @@ -218,7 +219,7 @@ protected function actionList($filter) * 注意:因为每个产品的评论可能加入了新的字段,因此不能使用ActiveRecord的方式取出来, * 使用下面的方式可以把字段都取出来。 */ - protected function actionGetByReviewId($_id) + public function getByReviewId($_id) { return $this->_reviewModel->getCollection()->findOne([$this->getPrimaryKey() => $_id]); } @@ -230,8 +231,10 @@ protected function actionGetByReviewId($_id) public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_reviewModel->findOne($primaryKey); } else { + return new $this->_reviewModelName(); } } @@ -269,7 +272,6 @@ public function save($one) $primaryVal = isset($one[$this->getPrimaryKey()]) ? $one[$this->getPrimaryKey()] : ''; $one['status'] = (int) $one['status']; $one['rate_star'] = (int) $one['rate_star']; - if ($primaryVal) { $model = $this->_reviewModel->findOne($primaryVal); if (!$model) { @@ -283,7 +285,6 @@ public function save($one) $primaryVal = new \MongoDB\BSON\ObjectId(); $model->{$this->getPrimaryKey()} = $primaryVal; } - //$review_data['status'] = $this->_reviewModel->ACTIVE_STATUS; $model->review_date = time(); unset($one[$this->getPrimaryKey()]); $saveStatus = Yii::$service->helper->ar->save($model, $one); @@ -340,7 +341,7 @@ public function remove($ids) * @param $ids | Array * 通过 $ids 数组,批量审核通过评论 */ - protected function actionAuditReviewByIds($ids) + public function auditReviewByIds($ids) { $reviewModel = $this->_reviewModel; if (is_array($ids) && !empty($ids)) { @@ -364,7 +365,7 @@ protected function actionAuditReviewByIds($ids) * @param $ids | Array * 通过 $ids 数组,批量审核评论拒绝 */ - protected function actionAuditRejectedReviewByIds($ids) + public function auditRejectedReviewByIds($ids) { $reviewModel = $this->_reviewModel; if (is_array($ids) && !empty($ids)) { @@ -388,7 +389,7 @@ protected function actionAuditRejectedReviewByIds($ids) * @param $spu | String * 当评论保存,更新评论的总数,平均评分信息到产品表的所有spu */ - protected function actionUpdateProductSpuReview($spu, $lang_code) + public function updateProductSpuReview($spu, $lang_code) { $reviewModel = $this->_reviewModel; $filter = [ @@ -409,7 +410,6 @@ protected function actionUpdateProductSpuReview($spu, $lang_code) $rate_total_arr['star_3'] = 0; $rate_total_arr['star_4'] = 0; $rate_total_arr['star_5'] = 0; - $rate_lang_total = 0; $rate_lang_total_arr['star_0'] = 0; $rate_lang_total_arr['star_1'] = 0; @@ -417,9 +417,6 @@ protected function actionUpdateProductSpuReview($spu, $lang_code) $rate_lang_total_arr['star_3'] = 0; $rate_lang_total_arr['star_4'] = 0; $rate_lang_total_arr['star_5'] = 0; - - - $lang_count = 0; if (!empty($data) && is_array($data)) { foreach ($data as $one) { @@ -466,7 +463,7 @@ protected function actionUpdateProductSpuReview($spu, $lang_code) * 'asArray' => true, * ] */ - protected function actionGetReviewsByUserId($filter) + public function getReviewsByUserId($filter) { $query = $this->_reviewModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); diff --git a/services/product/review/ReviewMysqldb.php b/services/product/review/ReviewMysqldb.php index 0f78cf8b9..e95839baa 100644 --- a/services/product/review/ReviewMysqldb.php +++ b/services/product/review/ReviewMysqldb.php @@ -52,13 +52,16 @@ public function getReviewService() public function isReviewRole($product_id) { if (!$this->getReviewService()->reviewOnlyOrderedProduct) { + return true; } $itmes = Yii::$service->order->item->getByProductIdAndCustomerId($product_id, $this->getReviewService()->reviewMonth); //var_dump($itmes);exit; if ($itmes) { + return true; } else { + return false; } } @@ -69,6 +72,7 @@ public function isReviewRole($product_id) public function noActiveStatus() { $model = $this->_reviewModel; + return $model::NOACTIVE_STATUS; } @@ -78,6 +82,7 @@ public function noActiveStatus() public function activeStatus() { $model = $this->_reviewModel; + return $model::ACTIVE_STATUS; } @@ -87,6 +92,7 @@ public function activeStatus() public function refuseStatus() { $model = $this->_reviewModel; + return $model::REFUSE_STATUS; } @@ -101,12 +107,11 @@ public function getPrimaryKey() * @param $spu | String. * 通过spu找到评论总数。 */ - protected function actionGetCountBySpu($spu) + public function getCountBySpu($spu) { $where = [ 'product_spu' => $spu, ]; - if ($this->getReviewService()->filterByLang && ($currentLangCode = Yii::$service->store->currentLangCode)) { $where['lang_code'] = $currentLangCode; } @@ -128,13 +133,12 @@ protected function actionGetCountBySpu($spu) * ] * 通过spu找到评论listing. */ - protected function actionGetListBySpu($filter) + public function getListBySpu($filter) { if ($this->getReviewService()->filterByLang && ($currentLangCode = Yii::$service->store->currentLangCode)) { $filter['where'][] = ['lang_code' => $currentLangCode]; } $query = $this->_reviewModel->find(); - $where = $filter['where']; $whereArr = []; // 对于 mongodb AR 的or查询的转换。 @@ -150,6 +154,7 @@ protected function actionGetListBySpu($filter) } } $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); + return [ 'coll' => $query->all(), 'count'=> $query->count(), @@ -161,7 +166,7 @@ protected function actionGetListBySpu($filter) * * 增加评论 前台增加评论调用的函数。 */ - protected function actionAddReview($review_data) + public function addReview($review_data) { //$this->initReviewAttr($review_data); $model = new $this->_reviewModelName(); @@ -170,7 +175,6 @@ protected function actionAddReview($review_data) } $model = $this->_reviewModel; $review_data['status'] = $model::NOACTIVE_STATUS; - $review_data['store'] = Yii::$service->store->currentStore; $review_data['lang_code'] = Yii::$service->store->currentLangCode; $review_data['review_date'] = time(); @@ -179,7 +183,6 @@ protected function actionAddReview($review_data) $user_id = $identity['id']; $review_data['user_id'] = $user_id; } - $review_data['ip'] = \fec\helpers\CFunc::get_real_ip(); $saveStatus = Yii::$service->helper->ar->save($model, $review_data); @@ -190,7 +193,7 @@ protected function actionAddReview($review_data) * @param $review_data | Array * 保存评论 */ - protected function actionUpdateReview($review_data) + public function updateReview($review_data) { //$this->initReviewAttr($review_data); $model = $this->_reviewModel->findOne([$this->getPrimaryKey()=> $review_data[$this->getPrimaryKey()]]); @@ -215,7 +218,7 @@ protected function actionUpdateReview($review_data) * ] * 查看review 的列表 */ - protected function actionList($filter) + public function list($filter) { $query = $this->_reviewModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); @@ -232,7 +235,7 @@ protected function actionList($filter) * 注意:因为每个产品的评论可能加入了新的字段,因此不能使用ActiveRecord的方式取出来, * 使用下面的方式可以把字段都取出来。 */ - protected function actionGetByReviewId($_id) + public function getByReviewId($_id) { return $this->_reviewModel->getCollection()->findOne([$this->getPrimaryKey() => $_id]); } @@ -244,8 +247,10 @@ protected function actionGetByReviewId($_id) public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_reviewModel->findOne($primaryKey); } else { + return new $this->_reviewModelName(); } } @@ -283,7 +288,6 @@ public function save($one) $primaryVal = isset($one[$this->getPrimaryKey()]) ? $one[$this->getPrimaryKey()] : ''; $one['status'] = (int) $one['status']; $one['rate_star'] = (int) $one['rate_star']; - if ($primaryVal) { $model = $this->_reviewModel->findOne($primaryVal); if (!$model) { @@ -294,7 +298,6 @@ public function save($one) } else { $model = new $this->_reviewModelName(); $model->created_admin_user_id = \fec\helpers\CUser::getCurrentUserId(); - } //$review_data['status'] = $this->_reviewModel->ACTIVE_STATUS; $model->review_date = time(); @@ -353,7 +356,7 @@ public function remove($ids) * @param $ids | Array * 通过 $ids 数组,批量审核通过评论 */ - protected function actionAuditReviewByIds($ids) + public function auditReviewByIds($ids) { $reviewModel = $this->_reviewModel; if (is_array($ids) && !empty($ids)) { @@ -377,7 +380,7 @@ protected function actionAuditReviewByIds($ids) * @param $ids | Array * 通过 $ids 数组,批量审核评论拒绝 */ - protected function actionAuditRejectedReviewByIds($ids) + public function auditRejectedReviewByIds($ids) { $reviewModel = $this->_reviewModel; if (is_array($ids) && !empty($ids)) { @@ -401,7 +404,7 @@ protected function actionAuditRejectedReviewByIds($ids) * @param $spu | String * 当评论保存,更新评论的总数,平均评分信息到产品表的所有spu */ - protected function actionUpdateProductSpuReview($spu, $lang_code) + public function updateProductSpuReview($spu, $lang_code) { $reviewModel = $this->_reviewModel; $filter = [ @@ -422,7 +425,6 @@ protected function actionUpdateProductSpuReview($spu, $lang_code) $rate_total_arr['star_3'] = 0; $rate_total_arr['star_4'] = 0; $rate_total_arr['star_5'] = 0; - $rate_lang_total = 0; $rate_lang_total_arr['star_0'] = 0; $rate_lang_total_arr['star_1'] = 0; @@ -430,9 +432,6 @@ protected function actionUpdateProductSpuReview($spu, $lang_code) $rate_lang_total_arr['star_3'] = 0; $rate_lang_total_arr['star_4'] = 0; $rate_lang_total_arr['star_5'] = 0; - - - $lang_count = 0; if (!empty($data) && is_array($data)) { foreach ($data as $one) { @@ -442,7 +441,6 @@ protected function actionUpdateProductSpuReview($spu, $lang_code) if ($lang_code == $one['lang_code']) { $rate_lang_total += $one['rate_star']; $lang_count++; - $rate_lang_total_arr[$rs] += 1; } } @@ -457,7 +455,6 @@ protected function actionUpdateProductSpuReview($spu, $lang_code) } else { $avag_lang_rate = ceil($rate_lang_total / $lang_count *10) / 10; } - Yii::$service->product->updateProductReviewInfo($spu, $avag_rate, $count, $lang_code, $avag_lang_rate, $lang_count, $rate_total_arr, $rate_lang_total_arr); return true; @@ -479,7 +476,7 @@ protected function actionUpdateProductSpuReview($spu, $lang_code) * 'asArray' => true, * ] */ - protected function actionGetReviewsByUserId($filter) + public function getReviewsByUserId($filter) { $query = $this->_reviewModel->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); diff --git a/services/product/viewLog/Db.php b/services/product/viewLog/Db.php index dce85880d..b011fd2d2 100644 --- a/services/product/viewLog/Db.php +++ b/services/product/viewLog/Db.php @@ -54,6 +54,7 @@ public function getHistory($user_id = '', $count = '') $user_id = CUser::getCurrentUserId(); } if (!$user_id) { + return; } $coll = $this->_logModel->find()->where([ diff --git a/services/product/viewLog/Mongodb.php b/services/product/viewLog/Mongodb.php index 7948cb0f0..14a92c189 100644 --- a/services/product/viewLog/Mongodb.php +++ b/services/product/viewLog/Mongodb.php @@ -55,6 +55,7 @@ public function getHistory($user_id = '', $count = '') $user_id = CUser::getCurrentUserId(); } if (!$user_id) { + return; } $coll = $this->_logModel->find()->where([ @@ -80,7 +81,6 @@ public function setHistory($productOb) 'image' => $productOb['image'], 'name' => $productOb['name'], ]; - if (isset($productOb['user_id']) && $productOb['user_id']) { $arr['user_id'] = $productOb['user_id']; } elseif ($currentUser = CUser::getCurrentUserId()) { @@ -89,7 +89,6 @@ public function setHistory($productOb) // if not give user_id, can not save history return; } - $mongodbViewLog = $this->_logModel->getCollection(); $mongodbViewLog->save($arr); } diff --git a/services/product/viewLog/Session.php b/services/product/viewLog/Session.php index d21e4a2bf..e27a164d9 100644 --- a/services/product/viewLog/Session.php +++ b/services/product/viewLog/Session.php @@ -57,7 +57,6 @@ public function setHistory($productOb) } else { $logArr['user_id'] = CUser::getCurrentUserId(); } - if (!($session_history = Yii::$service->session->get($this->_sessionKey))) { $session_history = []; } elseif (($count = count($session_history)) >= $this->_maxProductCount) { diff --git a/services/search/MongoSearch.php b/services/search/MongoSearch.php index af222a37a..9ebde74ac 100644 --- a/services/search/MongoSearch.php +++ b/services/search/MongoSearch.php @@ -24,8 +24,6 @@ class MongoSearch extends Service implements SearchInterface { public $searchIndexConfig; - //public $searchLang; - public $enable; // https://docs.mongodb.com/manual/reference/text-search-languages/#text-search-languages @@ -46,19 +44,16 @@ class MongoSearch extends Service implements SearchInterface 'sv' => 'swedish', 'tr' => 'turkish', ]; - - //protected $_productModelName = '\fecshop\models\mongodb\Product'; - - //protected $_productModel; - + protected $_searchModelName = '\fecshop\models\mongodb\Search'; protected $_searchModel; + protected $_searchLang; + public function init() { parent::init(); - //list($this->_productModelName, $this->_productModel) = \Yii::mapGet($this->_productModelName); list($this->_searchModelName, $this->_searchModel) = \Yii::mapGet($this->_searchModelName); $sModel = $this->_searchModel; /** @@ -74,8 +69,6 @@ public function init() } } - protected $_searchLang; - protected function getActiveLangConfig() { if (!$this->_searchLang) { @@ -88,13 +81,14 @@ protected function getActiveLangConfig() } } } + return $this->_searchLang; } /** * 创建索引. */ - protected function actionInitFullSearchIndex() + public function initFullSearchIndex() { $sModel = $this->_searchModel; $config1 = []; @@ -106,8 +100,6 @@ protected function actionInitFullSearchIndex() $config2['weights'][$column] = (int) $weight; } } - - //$langCodes = Yii::$service->fecshoplang->allLangCode; $searchLang = $this->getActiveLangConfig(); if (!empty($searchLang) && is_array($searchLang)) { foreach ($searchLang as $langCode => $mongoSearchLangName) { @@ -126,11 +118,11 @@ protected function actionInitFullSearchIndex() } } } - // + protected function getProductSelectData() { $productPrimaryKey = Yii::$service->product->getPrimaryKey(); - //echo $productPrimaryKey;exit; + return [ $productPrimaryKey, 'name', @@ -151,14 +143,13 @@ protected function getProductSelectData() 'description', 'created_at', ]; - } /** * @param $product_ids | Array ,里面的子项是MongoId类型。 * 将产品表的数据同步到各个语言对应的搜索表中。 */ - protected function actionSyncProductInfo($product_ids, $numPerPage) + public function syncProductInfo($product_ids, $numPerPage) { $sModel = $this->_searchModel; if (is_array($product_ids) && !empty($product_ids)) { @@ -169,8 +160,6 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) $filter['where'][] = ['in', $productPrimaryKey, $product_ids]; $filter['numPerPage'] = $numPerPage; $filter['pageNum'] = 1; - - $coll = Yii::$service->product->coll($filter); if (is_array($coll['coll']) && !empty($coll['coll'])) { $productPrimaryKey = Yii::$service->product->getPrimaryKey(); @@ -180,18 +169,13 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) $one['score'] = (int)$one['score']; $one['is_in_stock'] = (int)$one['is_in_stock']; $one['created_at'] = (int)$one['created_at']; - $one['price'] = (float)$one['price']; $one['cost_price'] = (float)$one['cost_price']; $one['special_price'] = (float)$one['special_price']; $one['special_from'] = (int)$one['special_from']; $one['special_to'] = (int)$one['special_to']; $one['final_price'] = (float)$one['final_price']; - unset($one[$productPrimaryKey]); - //$langCodes = Yii::$service->fecshoplang->allLangCode; - //if(!empty($langCodes) && is_array($langCodes)){ - // foreach($langCodes as $langCodeInfo){ $one_name = $one['name']; $one_description = $one['description']; $one_short_description = $one['short_description']; @@ -200,7 +184,6 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) foreach ($searchLang as $langCode => $mongoSearchLangName) { $sModel::$_lang = $langCode; $searchModel = $this->_searchModel->findOne(['product_id' => $one['product_id']]); - if (!$searchModel['product_id']) { $searchModel = new $this->_searchModelName(); } @@ -212,14 +195,12 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) if ($errors = Yii::$service->helper->errors->get()) { // 报错。 echo $errors; - //return false; } } } } } } - //echo "MongoSearch sync done ... \n"; return true; } @@ -229,7 +210,7 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) * 批量更新过程中,被更新的产品都会更新字段sync_updated_at * 删除xunSearch引擎中sync_updated_at小于$nowTimeStamp的字段. */ - protected function actionDeleteNotActiveProduct($nowTimeStamp) + public function deleteNotActiveProduct($nowTimeStamp) { $sModel = $this->_searchModel; echo "begin delete Mongodb Search Date \n"; @@ -254,7 +235,7 @@ protected function actionDeleteNotActiveProduct($nowTimeStamp) } } - protected function actionRemoveByProductId($product_id) + public function removeByProductId($product_id) { $sModel = $this->_searchModel; $searchLang = $this->getActiveLangConfig(); @@ -291,7 +272,7 @@ protected function actionRemoveByProductId($product_id) * ] * 得到搜索的产品列表. */ - protected function actionGetSearchProductColl($select, $where, $pageNum, $numPerPage, $product_search_max_count) + public function getSearchProductColl($select, $where, $pageNum, $numPerPage, $product_search_max_count) { // 先进行sku搜索,如果有结果,说明是针对sku的搜索 $enableStatus = Yii::$service->product->getEnableStatus(); @@ -308,11 +289,10 @@ protected function actionGetSearchProductColl($select, $where, $pageNum, $numPer 'product_search_max_count' => $product_search_max_count, 'select' => $select, ]; - //var_dump($filter);exit; $collection = $this->fullTearchText($filter); } $collection['coll'] = Yii::$service->category->product->convertToCategoryInfo($collection['coll']); - //var_dump($collection); + return $collection; } @@ -339,23 +319,16 @@ protected function fullTearchText($filter) $where['status'] = Yii::$service->product->getEnableStatus(); } $product_search_max_count = $filter['product_search_max_count'] ? $filter['product_search_max_count'] : 1000; - $select = $filter['select']; $pageNum = $filter['pageNum']; $numPerPage = $filter['numPerPage']; $orderBy = $filter['orderBy']; - // /* * 说明:1.'search_score'=>['$meta'=>"textScore" ,这个是text搜索为了排序, * 详细参看:https://docs.mongodb.com/manual/core/text-search-operators/ * 2. sort排序:search_score是全文搜索匹配后的得分,score是product表的一个字段,这个字段可以通过销售量或者其他作为参考设置。 */ $sModel::$_lang = Yii::$service->store->currentLangCode; - //$search_data = $this->_searchModel->getCollection(); - - //$mongodb = Yii::$app->mongodb; - //$search_data = $mongodb->getCollection('full_search_product_en') - $search_data = $this->_searchModel->getCollection()->find( $where, ['search_score'=>['$meta'=>'textScore'], 'id' => 1, 'spu'=> 1, 'score' => 1,'product_id' => 1], @@ -364,7 +337,6 @@ protected function fullTearchText($filter) 'limit'=> $product_search_max_count, ] ); - //var_dump($search_data);exit; /** * 在搜索页面, spu相同的sku,是否只显示其中score高的sku,其他的sku隐藏 * 如果设置为true,那么在搜索结果页面,spu相同,sku不同的产品,只会显示score最高的那个产品 @@ -381,8 +353,7 @@ protected function fullTearchText($filter) } } else { $data = $search_data; - } - + } $count = count($data); $offset = ($pageNum - 1) * $numPerPage; $limit = $numPerPage; @@ -390,11 +361,9 @@ protected function fullTearchText($filter) foreach ($data as $d) { $productIds[] = $d['product_id']; } - $productIds = array_slice($productIds, $offset, $limit); $productPrimaryKey = Yii::$service->product->getPrimaryKey(); if (!empty($productIds)) { - // foreach ($select as $sk => $se) { if ($se == 'product_id') { unset($select[$sk]); @@ -412,7 +381,6 @@ protected function fullTearchText($filter) /** * 下面的代码的作用:将结果按照上面in查询的顺序进行数组的排序,使结果和上面的搜索结果排序一致(_id)。 */ - //var_dump($data);exit; $s_data = []; foreach ($data as $one) { if ($one[$productPrimaryKey]) { @@ -441,9 +409,10 @@ protected function fullTearchText($filter) * 得到的是个属性,以及对应的个数。 * 这个功能是用于前端分类侧栏进行属性过滤。 */ - protected function actionGetFrontSearchFilter($filter_attr, $where) + public function getFrontSearchFilter($filter_attr, $where) { if (empty($where)) { + return []; } $group['_id'] = '$'.$filter_attr; diff --git a/services/search/MysqlSearch.php b/services/search/MysqlSearch.php index a41e0b3ff..bdafb7404 100644 --- a/services/search/MysqlSearch.php +++ b/services/search/MysqlSearch.php @@ -10,8 +10,6 @@ namespace fecshop\services\search; -//use fecshop\models\mongodb\Product; -//use fecshop\models\mongodb\Search; use fecshop\services\Service; use Yii; @@ -24,38 +22,32 @@ class MysqlSearch extends Service implements SearchInterface { public $searchIndexConfig; - //public $searchLang; - public $enable; - //protected $_productModelName = '\fecshop\models\mongodb\Product'; - - //protected $_productModel; - protected $_searchModelName = '\fecshop\models\mysqldb\Search'; protected $_searchModel; + protected $_searchLangCode; + public function init() { parent::init(); - //list($this->_productModelName, $this->_productModel) = \Yii::mapGet($this->_productModelName); list($this->_searchModelName, $this->_searchModel) = \Yii::mapGet($this->_searchModelName); - } /** * 创建索引. (mysql不需要) */ - protected function actionInitFullSearchIndex() + public function initFullSearchIndex() { return; } - // + protected function getProductSelectData() { $productPrimaryKey = Yii::$service->product->getPrimaryKey(); - //echo $productPrimaryKey;exit; + return [ $productPrimaryKey, 'name', @@ -78,7 +70,6 @@ protected function getProductSelectData() ]; } - protected $_searchLangCode; // 从配置中得到当前的搜索引擎对应的有效语言。 protected function getActiveLangCode() { @@ -90,13 +81,14 @@ protected function getActiveLangCode() } } } + return $this->_searchLangCode; } /** * @param $product_ids | Array ,里面的子项是MongoId类型。 * 将产品表的数据同步到各个语言对应的搜索表中。 */ - protected function actionSyncProductInfo($product_ids, $numPerPage) + public function syncProductInfo($product_ids, $numPerPage) { $sModel = $this->_searchModel; if (is_array($product_ids) && !empty($product_ids)) { @@ -107,8 +99,6 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) $filter['where'][] = ['in', $productPrimaryKey, $product_ids]; $filter['numPerPage'] = $numPerPage; $filter['pageNum'] = 1; - - $coll = Yii::$service->product->coll($filter); if (is_array($coll['coll']) && !empty($coll['coll'])) { $productPrimaryKey = Yii::$service->product->getPrimaryKey(); @@ -118,18 +108,13 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) $one['score'] = (int)$one['score']; $one['is_in_stock'] = (int)$one['is_in_stock']; $one['created_at'] = (int)$one['created_at']; - $one['price'] = (float)$one['price']; $one['cost_price'] = (float)$one['cost_price']; $one['special_price'] = (float)$one['special_price']; $one['special_from'] = (int)$one['special_from']; $one['special_to'] = (int)$one['special_to']; $one['final_price'] = (float)$one['final_price']; - unset($one[$productPrimaryKey]); - //$langCodes = Yii::$service->fecshoplang->allLangCode; - //if(!empty($langCodes) && is_array($langCodes)){ - // foreach($langCodes as $langCodeInfo){ $one_name = $one['name']; $one_description = $one['description']; $one_short_description = $one['short_description']; @@ -138,12 +123,10 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) foreach ($searchLangCode as $langCode) { $one['lang'] = $langCode; $one['image'] = serialize($one['image']); - $searchModel = $this->_searchModel->findOne([ 'product_id' => $one['product_id'], 'lang' => $langCode, ]); - if (!$searchModel['product_id']) { $searchModel = new $this->_searchModelName(); } @@ -155,14 +138,12 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) if ($errors = Yii::$service->helper->errors->get()) { // 报错。 var_dump($errors); - //return false; } } } } } } - //echo "MongoSearch sync done ... \n"; return true; } @@ -172,14 +153,13 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) * 批量更新过程中,被更新的产品都会更新字段sync_updated_at * 删除mysqlSearch引擎中sync_updated_at小于$nowTimeStamp的字段. */ - protected function actionDeleteNotActiveProduct($nowTimeStamp) + public function deleteNotActiveProduct($nowTimeStamp) { $sModel = $this->_searchModel; echo "begin delete Mongodb Search Date \n"; $searchLangCode = $this->getActiveLangCode(); if (!empty($searchLangCode) && is_array($searchLangCode)) { foreach ($searchLangCode as $langCode) { - //$sModel::$_lang = $langCode; // 更新时间方式删除。 $this->_searchModel->deleteAll([ 'and', @@ -196,7 +176,7 @@ protected function actionDeleteNotActiveProduct($nowTimeStamp) } } - protected function actionRemoveByProductId($product_id) + public function removeByProductId($product_id) { $this->_searchModel->deleteAll([ 'product_id' => $product_id, @@ -226,7 +206,7 @@ protected function actionRemoveByProductId($product_id) * ] * 得到搜索的产品列表. */ - protected function actionGetSearchProductColl($select, $where, $pageNum, $numPerPage, $product_search_max_count) + public function getSearchProductColl($select, $where, $pageNum, $numPerPage, $product_search_max_count) { // 先进行sku搜索,如果有结果,说明是针对sku的搜索 $enableStatus = Yii::$service->product->getEnableStatus(); @@ -243,11 +223,10 @@ protected function actionGetSearchProductColl($select, $where, $pageNum, $numPer 'product_search_max_count' => $product_search_max_count, 'select' => $select, ]; - //var_dump($filter);exit; $collection = $this->fullTearchText($filter); } $collection['coll'] = Yii::$service->category->product->convertToCategoryInfo($collection['coll']); - //var_dump($collection); + return $collection; } @@ -277,7 +256,6 @@ protected function fullTearchText($filter) if (!isset($where['status'])) { $where['status'] = Yii::$service->product->getEnableStatus(); } - //$product_search_max_count = $filter['product_search_max_count'] ? $filter['product_search_max_count'] : 1000; foreach ($where as $k=>$v) { if (is_array($v)) { $k !== 'price' || $k = 'final_price'; @@ -339,6 +317,7 @@ protected function fullTearchText($filter) ]; $collData = Yii::$service->product->coll($filter); $return_data = $collData['coll']; + return [ 'coll' => $return_data, 'count'=> $count, @@ -355,7 +334,7 @@ protected function fullTearchText($filter) * 这个功能是用于前端分类侧栏进行属性过滤。 * mysql 功能受限,这个废掉了。 */ - protected function actionGetFrontSearchFilter($filter_attr, $where) + public function getFrontSearchFilter($filter_attr, $where) { return []; } diff --git a/services/search/XunSearch.php b/services/search/XunSearch.php index 04cee5e1c..6f6d7f256 100644 --- a/services/search/XunSearch.php +++ b/services/search/XunSearch.php @@ -24,16 +24,12 @@ class XunSearch extends Service implements SearchInterface { public $searchIndexConfig; - //public $searchLang; - + protected $_searchLangCode; + public $fuzzy = false; public $synonyms = false; - //protected $_productModelName = '\fecshop\models\mongodb\Product'; - - //protected $_productModel; - protected $_searchModelName = '\fecshop\models\xunsearch\Search'; protected $_searchModel; @@ -41,20 +37,19 @@ class XunSearch extends Service implements SearchInterface public function init() { parent::init(); - //list($this->_productModelName, $this->_productModel) = \Yii::mapGet($this->_productModelName); list($this->_searchModelName, $this->_searchModel) = \Yii::mapGet($this->_searchModelName); } /** * 初始化xunSearch索引. */ - protected function actionInitFullSearchIndex() + public function initFullSearchIndex() { } protected function getProductSelectData() { $productPrimaryKey = Yii::$service->product->getPrimaryKey(); - //echo $productPrimaryKey;exit; + return [ $productPrimaryKey, 'name', @@ -75,9 +70,7 @@ protected function getProductSelectData() 'description', 'created_at', ]; - } - protected $_searchLangCode; protected function getActiveLangCode() { @@ -89,12 +82,13 @@ protected function getActiveLangCode() } } } + return $this->_searchLangCode; } /** * 将产品信息同步到xunSearch引擎中. */ - protected function actionSyncProductInfo($product_ids, $numPerPage) + public function syncProductInfo($product_ids, $numPerPage) { if (is_array($product_ids) && !empty($product_ids)) { $productPrimaryKey = Yii::$service->product->getPrimaryKey(); @@ -113,22 +107,18 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) $one['score'] = (int)$one['score']; $one['is_in_stock'] = (int)$one['is_in_stock']; $one['created_at'] = (int)$one['created_at']; - $one['price'] = (float)$one['price']; $one['cost_price'] = (float)$one['cost_price']; $one['special_price'] = (float)$one['special_price']; $one['special_from'] = (int)$one['special_from']; $one['special_to'] = (int)$one['special_to']; $one['final_price'] = (float)$one['final_price']; - //unset($one[$productPrimaryKey]); - $one_name = $one['name']; $one_description = $one['description']; $one_short_description = $one['short_description']; $searchLangCode = $this->getActiveLangCode(); if (!empty($searchLangCode) && is_array($searchLangCode)) { foreach ($searchLangCode as $langCode) { - //echo $langCode; $xunSearchModel = new $this->_searchModelName(); $xunSearchModel->_id = (string) $one[$productPrimaryKey]; $one['name'] = Yii::$service->fecshoplang->getLangAttrVal($one_name, 'name', $langCode); @@ -141,19 +131,17 @@ protected function actionSyncProductInfo($product_ids, $numPerPage) if ($errors = Yii::$service->helper->errors->get()) { // 报错。 var_dump($errors); - //return false; } } } } } } - //echo "XunSearch sync done ... \n"; return true; } - protected function actionDeleteNotActiveProduct($nowTimeStamp) + public function deleteNotActiveProduct($nowTimeStamp) { } @@ -163,14 +151,11 @@ protected function actionDeleteNotActiveProduct($nowTimeStamp) * 您希望也被删除掉,那么,你可以通过这种方式批量删除掉产品 * 然后重新跑一边同步脚本. */ - protected function actionXunDeleteAllProduct($numPerPage, $i) + public function xunDeleteAllProduct($numPerPage, $i) { - //var_dump($index); $dbName = $this->_searchModel->projectName(); // 删除索引 Yii::$app->xunsearch->getDatabase($dbName)->getIndex()->clean(); - //$index = Yii::$app->xunsearch->getDatabase($dbName)->index; - echo "begin delete Xun Search Date \n"; $nowTimeStamp = (int) $nowTimeStamp; $XunSearchData = $this->_searchModel->find() @@ -185,13 +170,11 @@ protected function actionXunDeleteAllProduct($numPerPage, $i) /** * 得到搜索的产品列表. */ - protected function actionGetSearchProductColl($select, $where, $pageNum, $numPerPage, $product_search_max_count) + public function getSearchProductColl($select, $where, $pageNum, $numPerPage, $product_search_max_count) { $collection = $this->fullTearchText($select, $where, $pageNum, $numPerPage, $product_search_max_count); - $collection['coll'] = Yii::$service->category->product->convertToCategoryInfo($collection['coll']); - //var_dump($collection); - //exit; + return $collection; } @@ -211,7 +194,6 @@ protected function fullTearchText($select, $where, $pageNum, $numPerPage, $produ $XunSearchQuery = $this->_searchModel->find()->asArray(); $XunSearchQuery->fuzzy($this->fuzzy); $XunSearchQuery->synonyms($this->synonyms); - if (is_array($where) && !empty($where)) { if (isset($where['$text']['$search']) && $where['$text']['$search']) { $XunSearchQuery->where($where['$text']['$search']); @@ -270,14 +252,11 @@ protected function fullTearchText($select, $where, $pageNum, $numPerPage, $produ } else { $productIds[] = $d['_id']; } - } $productIds = array_slice($productIds, $offset, $limit); } - $productPrimaryKey = Yii::$service->product->getPrimaryKey(); if (!empty($productIds)) { - // foreach ($select as $sk => $se) { if ($se == 'product_id') { unset($select[$sk]); @@ -295,7 +274,6 @@ protected function fullTearchText($select, $where, $pageNum, $numPerPage, $produ /** * 下面的代码的作用:将结果按照上面in查询的顺序进行数组的排序,使结果和上面的搜索结果排序一致(_id)。 */ - //var_dump($data);exit; $s_data = []; foreach ($data as $one) { if ($one[$productPrimaryKey]) { @@ -316,19 +294,18 @@ protected function fullTearchText($select, $where, $pageNum, $numPerPage, $produ 'count'=> $count, ]; } - } /** * 得到搜索的sku列表侧栏的过滤. */ - protected function actionGetFrontSearchFilter($filter_attr, $where) + public function getFrontSearchFilter($filter_attr, $where) { - //var_dump($where); $dbName = $this->_searchModel->projectName(); $_search = Yii::$app->xunsearch->getDatabase($dbName)->getSearch(); $text = isset($where['$text']['$search']) ? $where['$text']['$search'] : ''; if (!$text) { + return []; } $sh = ''; @@ -341,8 +318,6 @@ protected function actionGetFrontSearchFilter($filter_attr, $where) } } } - //echo $sh; - $docs = $_search->setQuery($text.$sh) ->setFacets([$filter_attr]) ->setFuzzy($this->fuzzy) @@ -365,7 +340,7 @@ protected function actionGetFrontSearchFilter($filter_attr, $where) /** * 通过product_id删除搜索数据. */ - protected function actionRemoveByProductId($product_id) + public function removeByProductId($product_id) { if (is_object($product_id)) { $product_id = (string) $product_id; diff --git a/services/url/Category.php b/services/url/Category.php index 7ff1ae21d..9e110a3de 100644 --- a/services/url/Category.php +++ b/services/url/Category.php @@ -25,20 +25,11 @@ class Category extends Service * @param $strVal | String * 把属性值转换成url格式的字符串,用于生成url. */ - protected function actionAttrValConvertUrlStr($strVal) + public function attrValConvertUrlStr($strVal) { if ($strVal) { + return urlencode($strVal); - // 如果在其他url重写的需要,可以在这里添加一下字符串转换,添加后 - // 函数actionUrlStrConvertAttrVal()也要做相应的转变 - //if (!preg_match('/^[A-Za-z0-9-_ &]+$/', $strVal)) { - // throw new InvalidValueException('"'.$strVal .'":contain special str , you can only contain special string [A-Za-z0-9-_ &]'); - //} - //$convert = $this->strUrlRelation(); - //foreach ($convert as $originStr => $nStr) { - // $strVal = str_replace($originStr, $nStr, $strVal); - //} - //return $strVal; } } @@ -46,16 +37,9 @@ protected function actionAttrValConvertUrlStr($strVal) * @param $urlStr | String * 把url格式的字符串转换成属性值,用于解析url,得到相应的属性值 */ - protected function actionUrlStrConvertAttrVal($urlStr) + public function urlStrConvertAttrVal($urlStr) { return urldecode($urlStr); - // 如果在其他url重写的需要,可以在这里添加一下字符串转换,添加后 - // 函数 actionAttrValConvertUrlStr()也要做相应的转变 - //$convert = $this->strUrlRelation(); - //foreach ($convert as $originStr => $nStr) { - // $urlStr = str_replace($nStr, $originStr, $urlStr); - //} - //return $urlStr; } /** @@ -76,7 +60,7 @@ protected function strUrlRelation() * @param $p|string 在url中用来表示分页的参数,一般用p来标示。 * @param $pageBackToOne|bool 是否让p的页数回归第一页 */ - protected function actionGetFilterChooseAttrUrl($attrUrlStr, $val, $p = 'p', $pageBackToOne = true) + public function getFilterChooseAttrUrl($attrUrlStr, $val, $p = 'p', $pageBackToOne = true) { $val = $this->attrValConvertUrlStr($val); $str = $attrUrlStr.'='.$val; @@ -89,7 +73,6 @@ protected function actionGetFilterChooseAttrUrl($attrUrlStr, $val, $p = 'p', $pa $afterPUrl = $p.'=1'; } } - if ($currentRequestVal) { $originAttrUrlStr = $attrUrlStr . '=' . $this->attrValConvertUrlStr($currentRequestVal); $currentUrl = Yii::$service->url->getCurrentUrl(); @@ -152,13 +135,12 @@ protected function actionGetFilterChooseAttrUrl($attrUrlStr, $val, $p = 'p', $pa * @param $p|string 在url中用来表示分页的参数,一般用p来标示。 * @param $pageBackToOne|bool 是否让p的页数回归第一页 */ - protected function actionGetFilterSortAttrUrl($arr, $p = '', $pageBackToOne = true) + public function getFilterSortAttrUrl($arr, $p = '', $pageBackToOne = true) { $sort = $arr['sort']['key']; $sortVal = $arr['sort']['val']; $dir = $arr['dir']['key']; $dirVal = $arr['dir']['val']; - $originPUrl = ''; if ($pageBackToOne && $p) { $pVal = Yii::$app->request->get($p); @@ -167,22 +149,17 @@ protected function actionGetFilterSortAttrUrl($arr, $p = '', $pageBackToOne = tr $afterPUrl = $p.'=1'; } } - $sortVal = $this->attrValConvertUrlStr($sortVal); $sortStr = $sort.'='.$sortVal; $currentSortVal = Yii::$app->request->get($sort); - $dirVal = $this->attrValConvertUrlStr($dirVal); $dirStr = $dir.'='.$dirVal; $currentDirVal = Yii::$app->request->get($dir); - $str = $sortStr.'&'.$dirStr; if ($currentSortVal && $currentDirVal) { $originAttrUrlStr = $sort.'='.$currentSortVal.'&'.$dir.'='.$currentDirVal; $currentUrl = Yii::$service->url->getCurrentUrl(); - if ($originAttrUrlStr == $str) { - //return str_replace($originAttrUrlStr,$str,$currentUrl); $url = $currentUrl; if (strstr($currentUrl, '?'.$originAttrUrlStr.'&')) { $url = str_replace('?'.$originAttrUrlStr.'&', '?', $currentUrl); @@ -235,7 +212,6 @@ protected function actionGetFilterSortAttrUrl($arr, $p = '', $pageBackToOne = tr } } - /** * 没有排序参数的url */ @@ -253,14 +229,4 @@ public function getFilterNoSortUrl() return $ar['scheme'].'://'.$ar['host'].$ar['path'].($arr ? '?'.http_build_query($arr) : ''); } - // 得到不选择这个属性的url - /* - protected function actionGetFilterUnChooseAttrUrl($attrUrlStr,$val){ - $val = $this->attrValConvertUrlStr($val); - $str = $attrUrlStr.'='.$val; - $currentUrl = Yii::$service->url->getCurrentUrl(); - $currentUrl = str_replace($str,'',$currentUrl); - return $currentUrl ; - } - */ } diff --git a/services/url/Rewrite.php b/services/url/Rewrite.php index 6a5023783..bb34039c7 100644 --- a/services/url/Rewrite.php +++ b/services/url/Rewrite.php @@ -53,7 +53,7 @@ public function init() * @param $urlKey | string * 通过重写后的urlkey字符串,去url_rewrite表中查询,找到重写前的url字符串。 */ - protected function actionGetOriginUrl($urlKey) + public function getOriginUrl($urlKey) { return $this->_urlRewrite->getOriginUrl($urlKey); } @@ -61,7 +61,7 @@ protected function actionGetOriginUrl($urlKey) /** * get artile's primary key. */ - protected function actionGetPrimaryKey() + public function getPrimaryKey() { return $this->_urlRewrite->getPrimaryKey(); } @@ -69,15 +69,11 @@ protected function actionGetPrimaryKey() /** * get artile model by primary key. */ - protected function actionGetByPrimaryKey($primaryKey) + public function getByPrimaryKey($primaryKey) { return $this->_urlRewrite->getByPrimaryKey($primaryKey); } - //public function getById($id){ - // return $this->_article->getById($id); - //} - /** * @param $filter|array * get artile collection by $filter @@ -94,7 +90,7 @@ protected function actionGetByPrimaryKey($primaryKey) * 'asArray' => true, * ] */ - protected function actionColl($filter = '') + public function coll($filter = '') { return $this->_urlRewrite->coll($filter); } @@ -104,7 +100,7 @@ protected function actionColl($filter = '') * @param $originUrlKey|string , article origin url key. * save $data to cms model,then,add url rewrite info to system service urlrewrite. */ - protected function actionSave($one) + public function save($one) { return $this->_urlRewrite->save($one); } @@ -113,7 +109,7 @@ protected function actionSave($one) * @param $ids | Array or String or Int * 删除相应的url rewrite 记录 */ - protected function actionRemove($ids) + public function remove($ids) { return $this->_urlRewrite->remove($ids); } @@ -122,7 +118,7 @@ protected function actionRemove($ids) * @param $time | Int * 根据updated_at 更新时间,删除相应的url rewrite 记录 */ - protected function actionRemoveByUpdatedAt($time) + public function removeByUpdatedAt($time) { return $this->_urlRewrite->removeByUpdatedAt($time); } @@ -130,7 +126,7 @@ protected function actionRemoveByUpdatedAt($time) /** * 返回url rewrite model 对应的query */ - protected function actionFind() + public function find() { return $this->_urlRewrite->find(); } @@ -138,7 +134,7 @@ protected function actionFind() /** * 返回url rewrite 查询结果 */ - protected function actionFindOne($where) + public function findOne($where) { return $this->_urlRewrite->findOne($where); } @@ -146,7 +142,7 @@ protected function actionFindOne($where) /** * 返回url rewrite model */ - protected function actionNewModel() + public function newModel() { return $this->_urlRewrite->newModel(); } diff --git a/services/url/rewrite/RewriteMongodb.php b/services/url/rewrite/RewriteMongodb.php index 5d8876d45..af419eaa5 100644 --- a/services/url/rewrite/RewriteMongodb.php +++ b/services/url/rewrite/RewriteMongodb.php @@ -44,6 +44,7 @@ public function getOriginUrl($urlKey) 'custom_url_key' => $urlKey, ])->asArray()->one(); if ($UrlData['custom_url_key']) { + return $UrlData['origin_url']; } } @@ -56,8 +57,10 @@ public function getPrimaryKey() public function getByPrimaryKey($primaryKey) { if ($primaryKey) { + return $this->_urlRewriteModel->findOne($primaryKey); } else { + return new $this->_urlRewriteModelName(); } } diff --git a/services/url/rewrite/RewriteMysqldb.php b/services/url/rewrite/RewriteMysqldb.php index b3a80d11c..80eb560d1 100644 --- a/services/url/rewrite/RewriteMysqldb.php +++ b/services/url/rewrite/RewriteMysqldb.php @@ -10,7 +10,6 @@ namespace fecshop\services\url\rewrite; -//use fecshop\models\mysqldb\url\UrlRewrite; use Yii; use fecshop\services\Service; use yii\base\InvalidValueException; @@ -50,6 +49,7 @@ public function getOriginUrl($urlKey) 'custom_url_key' => $urlKey, ])->asArray()->one(); if ($UrlData) { + return $UrlData['origin_url']; } } @@ -73,6 +73,7 @@ public function getByPrimaryKey($primaryKey) return $one; } else { + return new $this->_urlRewriteModelName(); } } @@ -106,7 +107,7 @@ public function coll($filter = '') $coll[$k] = $one; } } - //var_dump($one); + return [ 'coll' => $coll, 'count'=> $query->limit(null)->offset(null)->count(), @@ -156,8 +157,6 @@ public function remove($ids) $url_key = $model['url_key']; $model->delete(); } else { - - //throw new InvalidValueException("ID:$id is not exist."); Yii::$service->helper->errors->add('UrlRewrite Remove Errors:ID {id} is not exist.', ['id' => $id]); $innerTransaction->rollBack();