public function testSWishlist() { Yii::import('application.modules.shop.components.SWishList'); $product = ShopProduct::model()->active()->find(); $user = User::model()->find(); $this->assertTrue($user instanceof User); $this->assertTrue($product instanceof $product); $model = new SWishList($user->id); $this->assertTrue(is_array($model->getIds())); // Add right product if $this->assertTrue($model->add($product->id)); // Add wrong product id $this->assertFalse($model->add(time())); // Check if product added $this->assertNotEmpty($model->getIds()); $this->assertTrue($model->count() >= 1); // Check products loading and we have at least one product $products = $model->getProducts(); $this->assertNotEmpty($products); $this->assertTrue($products[0] instanceof ShopProduct); // Clear all $model->clear(); $this->assertEmpty($model->getIds()); // Removing $this->assertTrue($model->add($product->id)); $model->remove($product->id); $this->assertEmpty($model->getIds()); }
public function testProductDuplicate() { $model = ShopProduct::model()->find(); $duplicator = new SProductsDuplicator(); $clone = $duplicator->duplicateProduct($model); $this->assertEquals($clone->name, $model->name . $duplicator->getSuffix()); }
/** * Rate product * @param integer $id product id */ public function actionRateProduct($id) { $request = Yii::app()->request; if ($request->isAjaxRequest) { $model = ShopProduct::model()->active()->findByPk($id); $mod = 'product'; $rating = (int) $_GET['rating']; if ($model && in_array($rating, array(1, 2, 3, 4, 5))) { $model->votes += 1; $model->rating += $rating; $model->save(); $new = time(); $ratingModel = new RatingModel(); $ratingModel->mid = $id; $ratingModel->modul = $mod; $ratingModel->time = $new; $ratingModel->user_id = Yii::app()->user->getId(); $ratingModel->host = '127.0.0.1'; $ratingModel->save(); $cookie = new CHttpCookie($mod . "-" . $id, $id); $cookie->expire = time() + 60 * 60 * 24 * 60; Yii::app()->request->cookies[$mod . "-" . $id] = $cookie; return $this->widget('ext.rating.Rating', array('pid' => $id, 'rating' => $model->rating, 'votes' => $model->votes)); /* if($model->saveCounters(array( 'votes' => 1, 'rating' => $rating ))){ die('sss'); }else{ die($rating); } */ } } }
public function actionIndex() { header('Content-Type: application/json'); $json = array(); $product = ShopProduct::model()->findByPk(Yii::app()->request->getPost('product_id')); if (!$product) { throw new CHttpException(404); } $record = new ProductNotifications(); if (isset($_POST['ProductNotifications'])) { $record->attributes = array('email' => $_POST['ProductNotifications']['email']); $record->product_id = $product->id; if ($record->validate() && $record->hasEmail() === false) { $record->save(); $json['message'] = 'Мы сообщим вам когда товар появится в наличии'; $json['status'] = 'OK'; } else { $json['message'] = 'Ошибка'; $json['status'] = 'ERROR'; } } $json['data'] = $this->renderPartial('_form', array('model' => $record, 'product' => $product), true); echo CJSON::encode($json); // $this->render('_form', array('model' => $record, 'product' => $product)); }
public function actionRefreshViews() { $model = ShopProduct::model()->updateAll(array('views' => 0), 'views > 1'); if ($model) { $this->redirect(array('index')); } else { $this->redirect(array('index')); } }
/** * @return boolean */ public function afterSave() { $this->order->updateTotalPrice(); $this->order->updateDeliveryPrice(); if ($this->isNewRecord) { $product = ShopProduct::model()->findByPk($this->product_id); $product->decreaseQuantity(); } return parent::afterSave(); }
public function run() { $session = Yii::app()->session->get('views'); if (!empty($session)) { $list = ShopProduct::model()->findAllByPk(array_values($session)); } else { $list = array(); } $this->render($this->skin, array('list' => $list, 'session' => $session)); }
public function run() { $criteria = new CDbCriteria(); // $criteria->condition = '`t`.`manufacturer_id`=67'; $criteria->order = '`t`.`date_create` DESC'; $criteria->scopes = array('active'); $criteria->limit = $this->limit; $provider = new ActiveDataProvider(ShopProduct::model()->cache(Yii::app()->controller->cacheTime), array('criteria' => $criteria, 'pagination' => array('totalItemCount' => $this->limit, 'pageSize' => $this->limit))); $this->render('view', array('provider' => $provider)); }
public function testCompareIsWorkingOk() { $product = ShopProduct::model()->active()->find(); $this->assertTrue($product instanceof ShopProduct); $this->open(Yii::app()->createUrl('/shop/Product/view', array('url' => $product->url))); $this->clickAndWait('css=div.silver_clean.silver_button > button'); $this->assertTrue($this->isTextPresent('Продукт успешно добавлен в список сравнения')); $this->clickAndWait('xpath=//a[contains(.,"Товары на сравнение")]'); $this->assertTrue($this->isTextPresent(str_replace(' ', ' ', $product->name))); $this->clickAndWait('link=Удалить'); $this->assertTrue($this->isTextPresent('Нет результатов')); }
public function testTitle() { Yii::app()->settings->set('core', array('site_name' => microtime())); $this->open('/'); $this->assertEquals(Yii::app()->settings->get('core', 'site_name'), $this->getTitle()); // Find any active product $product = ShopProduct::model()->active()->find(); $this->assertTrue($product instanceof ShopProduct); // Open product page $this->open(Yii::app()->createUrl('/shop/product/view', array('seo_alias' => $product->seo_alias))); $this->assertEquals($product->name . ' / ' . Yii::app()->settings->get('core', 'site_name'), $this->getTitle()); }
public function actionXml() { header('Content-type: application/xml'); $products = ShopProduct::model()->findAll(); $productsList = array(); $productsList['products'] = array(); foreach ($products as $obj) { $productsList['products']['product'][] = array('@attributes' => array('id' => $obj->id), 'name' => $obj->name, 'price' => $obj->price); } $xml = Array2XML::createXML('shop', $productsList); echo $xml->saveXML(); Yii::app()->end(); }
/** * Creates copy of many products. * * @param array $ids of products to make copy * @param array $duplicate list of product parts to copy: images, variants, etc... * @return array of new product ids */ public function createCopy(array $ids, array $duplicate = array()) { // Yii::import('mod.shop.models.ShopProduct'); $this->duplicate = $duplicate; $new_ids = array(); foreach ($ids as $id) { $model = ShopProduct::model()->findByPk($id); if ($model) { $new_ids[] = $this->duplicateProduct($model)->id; } } return $new_ids; }
public function afterUninstall() { Yii::app()->settings->clear('shop'); Yii::app()->unintallComponent('currency'); $db = Yii::app()->db; $tablesArray = array(ShopTypeAttribute::model()->tableName(), ShopAttribute::model()->tableName(), ShopAttributeOption::model()->tableName(), ShopAttributeOptionTranslate::model()->tableName(), ShopAttributeTranslate::model()->tableName(), ShopCategory::model()->tableName(), ShopCategoryTranslate::model()->tableName(), ShopCurrency::model()->tableName(), ShopManufacturer::model()->tableName(), ShopManufacturerTranslate::model()->tableName(), ShopProduct::model()->tableName(), ShopProductCategoryRef::model()->tableName(), ShopProductImage::model()->tableName(), ShopProductTranslate::model()->tableName(), ShopProductType::model()->tableName(), ShopProductVariant::model()->tableName(), ShopRelatedProduct::model()->tableName(), ShopSuppliers::model()->tableName(), $db->tablePrefix . 'shop_product_attribute_eav', $db->tablePrefix . 'shop_product_configurable_attributes', $db->tablePrefix . 'shop_product_configurations'); foreach ($tablesArray as $table) { $db->createCommand()->dropTable($table); } CFileHelper::removeDirectory(Yii::getPathOfAlias('webroot.uploads.product'), array('traverseSymlinks' => true)); CFileHelper::removeDirectory(Yii::getPathOfAlias('webroot.uploads.categories'), array('traverseSymlinks' => true)); CFileHelper::removeDirectory(Yii::getPathOfAlias('webroot.uploads.manufacturer'), array('traverseSymlinks' => true)); return parent::afterUninstall(); }
/** * @param array $attributes */ public function export(array $attributes) { $limit = 10; $total = ceil(ShopProduct::model()->count() / $limit); $offset = 0; $row = array(); for ($i = 0; $i <= $total; ++$i) { $products = ShopProduct::model()->findAll(array('limit' => $limit, 'offset' => $offset)); foreach ($products as $pid => $p) { foreach ($attributes as $k => $attr) { if ($attr === 'category') { $value = $this->getCategory($p); } elseif ($attr === 'manufacturer') { $value = $this->getManufacturer($p); } elseif ($attr === 'images') { $images = array(); foreach ($p->images as $k => $image) { if ($image->is_main) { $images['image'][] = array('@value' => $image->name, '@attributes' => array('is_main' => true)); } else { $images['image'][] = array('@value' => $image->name); } } $value = $images; } elseif ($attr === 'additionalCategories') { $value = $this->getAdditionalCategories($p); } else { if (substr($attr, 0, 4) === 'eav_') { $v = substr($attr, 4); $row['product'][$pid]['attributes']['attribute'][] = array('@attributes' => array('name' => $v), '@value' => $p->{$attr}); } $value = $p->{$attr}; } if (substr($attr, 0, 4) !== 'eav_') { $row['product'][$pid][$attr] = $value; } } array_push($this->rows, $row); } $offset += $limit; } // print_r($row);die; header('Content-Type: text/html;charset=UTF-8'); header('Content-type: application/xml'); $xml = Array2XML::createXML('products', $row); echo $xml->saveXML(); Yii::app()->end(); $this->proccessOutput(); }
/** * @static * @param $type * @param $externalId * @param bool $loadModel */ public static function getObject($type, $externalId, $loadModel = true) { $query = Yii::app()->db->createCommand()->select("*")->from('{{exchange1c}}')->where('object_type=:type AND external_id=:externalId', array(':type' => $type, ':externalId' => $externalId))->limit(1)->queryRow(); if ($query === false) { return false; } if ($loadModel === true && $query['object_id']) { switch ($type) { case self::OBJECT_TYPE_CATEGORY: return ShopCategory::model()->findByPk($query['object_id']); break; case self::OBJECT_TYPE_ATTRIBUTE: return ShopAttribute::model()->findByPk($query['object_id']); break; case self::OBJECT_TYPE_PRODUCT: return ShopProduct::model()->findByPk($query['object_id']); break; } } return $query['object_id']; }
/** * Check creating new comment */ public function testCreateComment() { // Find any active product $product = ShopProduct::model()->active()->find(); $this->assertTrue($product instanceof ShopProduct); $email = '*****@*****.**'; $text = 'this is test comment' . microtime(); // Open product page and post comment $this->open(Yii::app()->createAbsoluteUrl('/shop/product/view', array('seo_alias' => $product->seo_alias))); $this->type('id=Comment_name', 'tester'); $this->type('id=Comment_email', $email); $this->type('id=Comment_text', $text); $this->clickAndWait("//input[@value='Отправить']"); $this->open(Yii::app()->createAbsoluteUrl('/shop/product/view', array('seo_alias' => $product->seo_alias))); $this->assertTrue($this->isTextPresent('Ваш комментарий успешно добавлен. Он будет опубликован после проверки администратором.')); $this->adminLogin(); $this->open('/admin/shop/products/update?id=' . $product->id); $this->click('xpath=//a[contains(.,"Отзывы")]'); $this->assertTrue($this->isTextPresent($email)); $this->assertTrue($this->isTextPresent($text)); }
public function testCompare() { Yii::import('application.modules.shop.components.SCompareProducts'); $product = ShopProduct::model()->active()->find(); $model = new SCompareProducts(); $this->assertTrue($model->session instanceof ArrayAccess); $this->assertTrue(is_array($model->getIds())); $this->assertTrue($model->add($product->id)); $this->assertFalse($model->add(time())); $this->assertNotEmpty($model->getIds()); $this->assertTrue($model->count() === 1); $products = $model->getProducts(); $this->assertNotEmpty($products); $this->assertTrue($products[0] instanceof ShopProduct); $this->assertTrue(is_array($model->getAttributes())); $model->clear(); $this->assertEmpty($model->getIds()); // Removing $this->assertTrue($model->add($product->id)); $model->remove($product->id); $this->assertEmpty($model->getIds()); }
public function testWishlist() { Yii::import('application.modules.shop.models.wishlist.*'); $wishlist = ShopWishlist::model()->find(); $product = ShopProduct::model()->active()->find(); $this->assertTrue($product instanceof ShopProduct); $this->open(Yii::app()->createUrl('/shop/Product/view', array('url' => $product->url))); $this->clickAndWait('xpath=//button[contains(.,"Список желаний")]'); $this->assertTrue($this->isTextPresent('Авторизация')); $this->type('id=UserLoginForm_username', 'admin'); $this->type('id=UserLoginForm_password', 'admin'); // Click on login button $this->clickAndWait('css=input.blue_button'); $this->open(Yii::app()->createUrl('/shop/Product/view', array('url' => $product->url))); $this->assertTrue($this->isTextPresent('Список желаний')); $this->clickAndWait('xpath=//button[contains(.,"Список желаний")]'); $this->assertTrue($this->isTextPresent('Продукт успешно добавлен в список желаний.')); $this->assertTrue($this->isTextPresent(str_replace(' ', ' ', $product->name))); // View wishlist view $this->open(Yii::app()->createAbsoluteUrl('/shop/wishlist/view', array('key' => $wishlist->key))); $this->assertTrue($this->isTextPresent('Список желаний')); $this->assertTrue($this->isTextPresent($product->name)); }
/** * @param array $attributes */ public function export(array $attributes) { $this->rows[0] = $attributes; foreach ($this->rows[0] as &$v) { if (substr($v, 0, 4) === 'eav_') { $v = substr($v, 4); } } $limit = 10; $total = ceil(ShopProduct::model()->count() / $limit); $offset = 0; for ($i = 0; $i <= $total; ++$i) { $products = ShopProduct::model()->findAll(array('limit' => $limit, 'offset' => $offset)); foreach ($products as $p) { $row = array(); foreach ($attributes as $attr) { if ($attr === 'category') { $value = $this->getCategory($p); } elseif ($attr === 'manufacturer') { $value = $this->getManufacturer($p); } elseif ($attr === 'image') { $value = $p->mainImage ? $p->mainImage->name : ''; } elseif ($attr === 'additionalCategories') { $value = $this->getAdditionalCategories($p); } else { $value = $p->{$attr}; } $row[$attr] = iconv('utf-8', 'cp1251', $value); //append iconv by panix } array_push($this->rows, $row); } $offset += $limit; } $this->proccessOutput(); }
/** * Assign categories to products */ public function actionAssignCategories() { $categories = Yii::app()->request->getPost('category_ids'); $products = Yii::app()->request->getPost('product_ids'); if (empty($categories) || empty($products)) { return; } $products = ShopProduct::model()->findAllByPk($products); foreach ($products as $p) { $p->setCategories($categories, Yii::app()->request->getPost('main_category')); } }
/** * @return array of ShopProduct models to compare */ public function getProducts() { if ($this->_products === null) { $this->_products = ShopProduct::model()->findAllByPk(array_values($this->getIds())); } return $this->_products; }
/** * @param $limit * @return array */ protected function getNewest($limit) { return ShopProduct::model()->cache($this->cacheTime)->active()->newest()->findAll(array('limit' => $limit)); }
/** * Get data to render dropdowns for configurable product. * Used on product view. * array( * 'attributes' // Array of ShopAttribute models used for configurations * 'prices' // Key/value array with configurations prices array(product_id=>price) * 'data' // Array to render dropdowns. array(color=>array('Green'=>'1/3/5/', 'Silver'=>'7/')) * ) * @todo Optimize. Cache queries. * @return array */ public function getConfigurableData() { $attributeModels = ShopAttribute::model()->cache($this->cacheTime)->findAllByPk($this->model->configurable_attributes); $models = ShopProduct::model()->cache($this->cacheTime)->findAllByPk($this->model->configurations); $data = array(); $prices = array(); foreach ($attributeModels as $attr) { foreach ($models as $m) { $prices[$m->id] = $m->price; if (!isset($data[$attr->name])) { $data[$attr->name] = array('---' => '0'); } $method = 'eav_' . $attr->name; $value = $m->{$method}; if (!isset($data[$attr->name][$value])) { $data[$attr->name][$value] = ''; } $data[$attr->name][$value] .= $m->id . '/'; } } return array('attributes' => $attributeModels, 'prices' => $prices, 'data' => $data); }
public function afterDelete() { // Clear product relations ShopProduct::model()->updateAll(array('manufacturer_id' => new CDbExpression('NULL')), 'manufacturer_id = :id', array(':id' => $this->id)); return parent::afterDelete(); }
Yii::import('mod.shop.models.ShopProduct'); ?> <div class="row"> <div class="col-xs-12"> <h3 class="slider-title">Популярные</h3> </div> </div> <div class="row"> <div class="owl-carousel home-slider custom-carousel owl-theme" data-item="3"> <?php $this->renderPartial('//layouts/partials/_slider_hit', array('id' => 'featured', 'model' => ShopProduct::model()->newest()->findAll(array('limit' => 16)))); ?> </div> </div> <div class="row"> <div class="col-xs-12"> <h3 class="slider-title">Популярные</h3> </div> </div> <div class="row"> <div class="owl-carousel home-slider custom-carousel owl-theme" data-item="3"> <?php $this->renderPartial('//layouts/partials/_slider_hit', array('id' => 'featured', 'model' => ShopProduct::model()->newest()->findAll(array('limit' => 16)))); ?> </div> </div>
/** * Calculate product price by its variants, configuration and self price * @static * @param $product * @param array $variants * @param $configuration */ public static function calculatePrices($product, array $variants, $configuration) { if ($product instanceof ShopProduct === false) { $product = ShopProduct::model()->findByPk($product); } if ($configuration instanceof ShopProduct === false && $configuration > 0) { $configuration = ShopProduct::model()->findByPk($configuration); } if ($configuration instanceof ShopProduct) { $result = $configuration->price; } else { //$result = ($product->currency_id)? $product->price: $product->price; $result = $product->price; } // if $variants contains not models if (!empty($variants) && $variants[0] instanceof ShopProductVariant === false) { $variants = ShopProductVariant::model()->findAllByPk($variants); } foreach ($variants as $variant) { // Price is percent if ($variant->price_type == 1) { $result += $result / 100 * $variant->price; } else { $result += $variant->price; } } return $result; }
public function afterDelete() { //Remove all products with this category set as main. $products = ShopProductCategoryRef::model()->findAllByAttributes(array('category' => $this->id, 'is_main' => '1')); foreach ($products as $p) { $productModel = ShopProduct::model()->findByPk($p->product); if ($productModel) { $productModel->delete(); } } // Remove all category-product relations ShopProductCategoryRef::model()->deleteAllByAttributes(array('category' => $this->id, 'is_main' => '0')); $this->clearRouteCache(); return parent::afterDelete(); }
/** * Validate POST data and add product to cart */ public function actionAdd() { $variants = array(); // Load product model $model = ShopProduct::model()->cache($this->cacheTime)->active()->findByPk(Yii::app()->request->getPost('product_id', 0)); // Check product if (!isset($model)) { $this->_addError(Yii::t('CartModule.default', 'ERROR_PRODUCT_NO_FIND'), true); } // Update counter $model->saveCounters(array('added_to_cart_count' => 1)); // Process variants if (!empty($_POST['eav'])) { foreach ($_POST['eav'] as $attribute_id => $variant_id) { if (!empty($variant_id)) { // Check if attribute/option exists if (!$this->_checkVariantExists($_POST['product_id'], $attribute_id, $variant_id)) { $this->_addError(Yii::t('CartModule.default', 'ERROR_VARIANT_NO_FIND')); } else { array_push($variants, $variant_id); } } } } // Process configurable products if ($model->use_configurations) { // Get last configurable item $configurable_id = Yii::app()->request->getPost('configurable_id', 0); if (!$configurable_id || !in_array($configurable_id, $model->configurations)) { $this->_addError(Yii::t('CartModule.default', 'ERROR_SELECT_VARIANT'), true); } } else { $configurable_id = 0; } Yii::app()->cart->add(array('product_id' => $model->id, 'variants' => $variants, 'currency_id' => $model->currency_id, 'supplier_id' => $model->supplier_id, 'pcs' => $model->pcs, 'configurable_id' => $configurable_id, 'quantity' => (int) Yii::app()->request->getPost('quantity', 1), 'price' => $model->price)); $this->_finish($model->name); }
public function ajaxRecount($data) { if (!is_array($data) || empty($data)) { return; } $currentData = $this->getData(); foreach ($data as $index => $quantity) { if ((int) $quantity < 1) { $quantity = 1; } if (isset($currentData[$index])) { $currentData[$index]['quantity'] = (int) $quantity; $data = $currentData[$index]; //print_r($currentData[$index]);die; if ($data['configurable_id']) { $productModel = ShopProduct::model()->findByPk($index); $rowTotal = $data['quantity'] * ShopProduct::calculatePrices($productModel, $data['variants'], $data['configurable_id']); } else { if (Yii::app()->settings->get('shop', 'wholesale')) { $rowTotal = $data['quantity'] * $data['pcs'] * $data['price']; } else { $rowTotal = $data['quantity'] * $data['price']; } } } } $this->session['cart_data'] = $currentData; echo CJSON::encode(array('rowTotal' => ShopProduct::formatPrice(Yii::app()->currency->convert($rowTotal)), 'totalPrice' => ShopProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice())))); }
/** * @return array of category manufacturers */ public function getCategoryManufacturers() { $cr = new CDbCriteria(); $cr->select = 't.manufacturer_id, t.id'; $cr->group = 't.manufacturer_id'; $cr->addCondition('t.manufacturer_id IS NOT NULL'); //@todo: Fix manufacturer translation $mdl = $this->model; $dependency = new CDbCacheDependency('SELECT MAX(date_update) FROM {{shop_product}}'); //$dependency = new CChainedCacheDependency(); $manufacturers = ShopProduct::model()->cache($this->controller->cacheTime, $dependency)->active()->applyCategories($mdl, null)->with(array('manufacturer' => array('with' => array('productsCount' => array('scopes' => array('active', 'applyCategories' => array($mdl, null), 'applyAttributes' => array($this->getOwner()->activeAttributes), 'applyMinPrice' => array($this->convertCurrency(Yii::app()->request->getQuery('min_price'))), 'applyMaxPrice' => array($this->convertCurrency(Yii::app()->request->getQuery('max_price')))))))))->findAll($cr); $data = array('title' => Yii::t('default', 'Производитель'), 'selectMany' => true, 'filters' => array()); if ($manufacturers) { foreach ($manufacturers as $m) { $m = $m->manufacturer; if ($m) { $model = new ShopProduct(null); $model->attachBehaviors($model->behaviors()); $model->active()->cache($this->controller->cacheTime, $dependency)->applyCategories($this->model)->applyMinPrice($this->convertCurrency(Yii::app()->request->getQuery('min_price')))->applyMaxPrice($this->convertCurrency(Yii::app()->request->getQuery('max_price')))->applyAttributes($this->getOwner()->activeAttributes)->applyManufacturers($m->id); $data['filters'][] = array('title' => $m->name, 'count' => $model->count(), 'queryKey' => 'manufacturer', 'queryParam' => $m->id); } } } return $data; }