/** * Display products by manufacturer * * @param $url * @throws CHttpException */ public function actionIndex($url) { $this->model = StoreManufacturer::model()->findByAttributes(array('url' => $url)); if (!$this->model) { throw new CHttpException(404, Yii::t('StoreModule.core', 'Производитель не найден.')); } $query = new StoreProduct(null); $query->attachBehaviors($query->behaviors()); $query->active(); $query->applyManufacturers($this->model->id); $provider = new CActiveDataProvider($query, array('id' => false, 'pagination' => array('pageSize' => $this->allowedPageLimit[0]))); $this->render('index', array('provider' => $provider)); }
/** * Check creating new orders */ public function testCreateOrder() { $microTime = microtime(); $comment = 'test comment ' . $microTime; // Find any active product $product = StoreProduct::model()->active()->findByAttributes(array('use_configurations' => 0)); $this->assertTrue($product instanceof StoreProduct); // Open product page and add to cart $this->open(Yii::app()->createUrl('/store/frontProduct/view', array('url' => $product->url))); $this->click("//input[@id='buyButton']"); $this->open('cart'); $this->assertTrue($this->isTextPresent($product->name)); $this->click('css=label.radio > span'); $this->type('id=OrderCreateForm_name', 'Tester Name'); $this->type('id=OrderCreateForm_email', '*****@*****.**'); $this->type('id=OrderCreateForm_phone', '0990000000'); $this->type('id=OrderCreateForm_address', 'test address'); $this->type('id=OrderCreateForm_comment', $comment); $this->clickAtAndWait('name=create'); // Check if order successfully saved $order = Order::model()->findByAttributes(array('user_comment' => $comment)); $this->assertTrue($order instanceof Order); // Check of ordered products $this->assertTrue($order->getOrderedProducts() instanceof CActiveDataProvider); $this->assertTrue($order->getOrderedProducts()->getTotalItemCount() > 0); }
public function testProductDuplicate() { $model = StoreProduct::model()->find(); $duplicator = new SProductsDuplicator(); $clone = $duplicator->duplicateProduct($model); $this->assertEquals($clone->name, $model->name . $duplicator->getSuffix()); }
/** * @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(StoreProduct::model()->count() / $limit); $offset = 0; for ($i = 0; $i <= $total; ++$i) { $products = StoreProduct::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] = $value; } array_push($this->rows, $row); } $offset += $limit; } $this->proccessOutput(); }
public function testSWishlist() { Yii::import('application.modules.store.components.SWishList'); $product = StoreProduct::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 StoreProduct); // Clear all $model->clear(); $this->assertEmpty($model->getIds()); // Removing $this->assertTrue($model->add($product->id)); $model->remove($product->id); $this->assertEmpty($model->getIds()); }
/** * Sum orders total price * * @return string */ public function getOrdersTotalPrice() { $total = 0; foreach ($this->getTodayOrders()->getData() as $order) { $total += $order->full_price; } return StoreProduct::formatPrice($total); }
/** * @return boolean */ public function afterSave() { $this->order->updateTotalPrice(); $this->order->updateDeliveryPrice(); if ($this->isNewRecord) { $product = StoreProduct::model()->findByPk($this->product_id); $product->decreaseQuantity(); } return parent::afterSave(); }
public function testTitle() { Yii::app()->settings->set('core', array('siteName' => microtime())); $this->open('/'); $this->assertEquals(Yii::app()->settings->get('core', 'siteName'), $this->getTitle()); // Find any active product $product = StoreProduct::model()->active()->find(); $this->assertTrue($product instanceof StoreProduct); // Open product page $this->open(Yii::app()->createUrl('/store/frontProduct/view', array('url' => $product->url))); $this->assertEquals($product->name . ' / ' . Yii::app()->settings->get('core', 'siteName'), $this->getTitle()); }
public function testCompareIsWorkingOk() { $product = StoreProduct::model()->active()->find(); $this->assertTrue($product instanceof StoreProduct); $this->open(Yii::app()->createUrl('/store/frontProduct/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('Нет результатов')); }
/** * Import default demo data */ private function importCsvFiles() { $files = array('laptops', 'computer_sound', 'monitors', 'phones', 'tablets'); foreach ($files as $file) { $importer = new CsvImporter(); $importer->file = Yii::getPathOfAlias('application.modules.install.data') . DIRECTORY_SEPARATOR . $file . '.csv'; if ($importer->validate() && !$importer->hasErrors()) { $importer->import(); } } StoreProduct::model()->updateAll(array('is_active' => 1)); }
/** * Add new email to list */ public function actionIndex() { $product = StoreProduct::model()->findByPk(Yii::app()->request->getPost('product_id')); if (!$product) { throw new CHttpException(404); } $record = new ProductNotifications(); $record->attributes = array('email' => $_POST['email']); $record->product_id = $product->id; if ($record->validate() && $record->hasEmail() === false) { $record->save(); } }
/** * Rate product * @param integer $id product id */ public function actionRateProduct($id) { $request = Yii::app()->request; if ($request->isAjaxRequest) { $model = StoreProduct::model()->active()->findByPk($id); $cookieName = 'rating_' . $model->id; $rating = (int) $_GET['rating']; if ($model && in_array($rating, array(1, 2, 3, 4, 5))) { $model->saveCounters(array('votes' => 1, 'rating' => $rating)); $cookie = new CHttpCookie($cookieName, true); $cookie->expire = time() + 60 * 60 * 24 * 60; Yii::app()->request->cookies[$cookieName] = $cookie; } } }
public function applyPricesFilter() { $minPrice = Yii::app()->request->getQuery('min_price'); $maxPrice = Yii::app()->request->getQuery('max_price'); $cm = Yii::app()->currency; if ($cm->active->id !== $cm->main->id && ($minPrice > 0 || $maxPrice > 0)) { $minPrice = $cm->activeToMain($minPrice); $maxPrice = $cm->activeToMain($maxPrice); } if ($minPrice > 0) { $this->query->applyMinPrice($minPrice); } if ($maxPrice > 0) { $this->query->applyMaxPrice($maxPrice); } }
/** * Check creating new comment */ public function testCreateComment() { // Find any active product $product = StoreProduct::model()->active()->find(); $this->assertTrue($product instanceof StoreProduct); $email = '*****@*****.**'; $text = 'this is test comment' . microtime(); // Open product page and post comment $this->open(Yii::app()->createAbsoluteUrl('/store/frontProduct/view', array('url' => $product->url))); $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('/store/frontProduct/view', array('url' => $product->url))); $this->assertTrue($this->isTextPresent('Ваш комментарий успешно добавлен. Он будет опубликован после проверки администратором.')); $this->adminLogin(); $this->open('/admin/store/products/update?id=' . $product->id); $this->click('xpath=//a[contains(.,"Отзывы")]'); $this->assertTrue($this->isTextPresent($email)); $this->assertTrue($this->isTextPresent($text)); }
/** * @static * @param $type * @param $externalId * @param bool $loadModel */ public static function getObject($type, $externalId, $loadModel = true) { $query = Yii::app()->db->createCommand()->select("*")->from('accounting1c')->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 StoreCategory::model()->findByPk($query['object_id']); break; case self::OBJECT_TYPE_ATTRIBUTE: return StoreAttribute::model()->findByPk($query['object_id']); break; case self::OBJECT_TYPE_PRODUCT: return StoreProduct::model()->findByPk($query['object_id']); break; } } return $query['object_id']; }
public function testCompare() { Yii::import('application.modules.store.components.SCompareProducts'); $product = StoreProduct::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 StoreProduct); $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()); }
/** * Get data to render dropdowns for configurable product. * Used on product view. * array( * 'attributes' // Array of StoreAttribute 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 = StoreAttribute::model()->findAllByPk($this->model->configurable_attributes); $models = StoreProduct::model()->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 testAccounting1cImport() { Yii::import('application.modules.accounting1c.components.C1ProductsImport'); $tempDir = Yii::getPathOfAlias(Yii::app()->settings->get('accounting1c', 'tempdir')); $importXml = Yii::getPathOfAlias('application.modules.accounting1c.tests.data') . DIRECTORY_SEPARATOR . 'import.xml'; $offersXml = Yii::getPathOfAlias('application.modules.accounting1c.tests.data') . DIRECTORY_SEPARATOR . 'offers.xml'; copy($importXml, $tempDir . DIRECTORY_SEPARATOR . 'import.xml'); copy($offersXml, $tempDir . DIRECTORY_SEPARATOR . 'offers.xml'); $_GET['filename'] = 'import.xml'; ob_start(); C1ProductsImport::processRequest('catalog', 'import'); $result = ob_get_contents(); ob_end_clean(); $this->assertTrue(trim($result) == 'success'); // Offers $_GET['filename'] = 'offers.xml'; ob_start(); C1ProductsImport::processRequest('catalog', 'import'); $result = ob_get_contents(); ob_end_clean(); $this->assertTrue(trim($result) == 'success'); $import = new C1ProductsImport(); $xml = $import->getXml('import.xml'); $this->assertTrue($xml instanceof SimpleXMLElement); foreach ($xml->{"Каталог"}->{"Товары"}->{"Товар"} as $product) { $cr = new CDbCriteria(); $cr->condition = 'translate.name=:name'; $cr->params = array(':name' => $product->{"Наименование"}); $model = StoreProduct::model()->applyTranslateCriteria()->find($cr); $this->assertTrue($model->name == $product->{"Наименование"}); } // Check attribute $model = StoreProduct::model()->findByAttributes(array('sku' => 'VAX-8002')); $attr = 'eav_kod_virobnika'; $this->assertTrue($model->{$attr} == 'VAX-8002'); $this->assertTrue($model->price == '9'); // Check category $this->assertTrue($model->mainCategory->name == 'Сумки для цифрового обладнання'); }
public function testWishlist() { Yii::import('application.modules.store.models.wishlist.*'); $wishlist = StoreWishlist::model()->find(); $product = StoreProduct::model()->active()->find(); $this->assertTrue($product instanceof StoreProduct); $this->open(Yii::app()->createUrl('/store/frontProduct/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('/store/frontProduct/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('/store/wishlist/view', array('key' => $wishlist->key))); $this->assertTrue($this->isTextPresent('Список желаний')); $this->assertTrue($this->isTextPresent($product->name)); }
<?php /** * Small cart. * This template is loaded thru ajax request after new product added to cart. */ ?> <div class="cart_left"></div> <div class="cart_right"> <a href="<?php echo Yii::app()->createUrl('/orders/cart/index'); ?> " class="light"> <?php echo Yii::app()->cart->countItems(); ?> товаров - <?php echo StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice())); ?> <?php echo Yii::app()->currency->active->symbol; ?> </a> </div>
/** * Import catalog products */ public function importProducts() { foreach ($this->xml->{"Каталог"}->{"Товары"}->{"Товар"} as $product) { $createExId = false; $model = C1ExternalFinder::getObject(C1ExternalFinder::OBJECT_TYPE_PRODUCT, $product->{"Ид"}); if (!$model) { $model = new StoreProduct(); $model->type_id = self::DEFAULT_TYPE; $model->price = 0; $model->is_active = 1; $createExId = true; } $model->name = $product->{"Наименование"}; $model->sku = $product->{"Артикул"}; $model->save(); // Create external id if ($createExId === true) { $this->createExternalId(C1ExternalFinder::OBJECT_TYPE_PRODUCT, $model->id, $product->{"Ид"}); } // Set category $categoryId = C1ExternalFinder::getObject(C1ExternalFinder::OBJECT_TYPE_CATEGORY, $product->{"Группы"}->{"Ид"}, false); $model->setCategories(array($categoryId), $categoryId); // Set image $image = C1ProductImage::create($this->buildPathToTempFile($product->{"Картинка"})); if ($image && !$model->mainImage) { $model->addImage($image); } // Process properties if (isset($product->{"ЗначенияСвойств"}->{"ЗначенияСвойства"})) { $attrsdata = array(); foreach ($product->{"ЗначенияСвойств"}->{"ЗначенияСвойства"} as $attribute) { $attributeModel = C1ExternalFinder::getObject(C1ExternalFinder::OBJECT_TYPE_ATTRIBUTE, $attribute->{"Ид"}); if ($attributeModel && $attribute->{"Значение"} != '') { $cr = new CDbCriteria(); $cr->with = 'option_translate'; $cr->compare('option_translate.value', $attribute->{"Значение"}); $option = StoreAttributeOption::model()->find($cr); if (!$option) { $option = $this->addOptionToAttribute($attributeModel->id, $attribute->{"Значение"}); } $attrsdata[$attributeModel->name] = $option->id; } } if (!empty($attrsdata)) { $model->setEavAttributes($attrsdata, true); } } } }
$this->renderPartial('_configurations', array('model' => $model)); ?> <div class="errors" id="productErrors"></div> <div style="clear: both;font-size: 16px"> <?php if ($model->appliedDiscount) { echo '<span style="color:red; "><s>' . $model->toCurrentCurrency('originalPrice') . ' ' . Yii::app()->currency->active->symbol . '</s></span>'; } ?> </div> <div class="price"> <span id="productPrice"><?php echo StoreProduct::formatPrice($model->toCurrentCurrency()); ?> </span> <?php echo Yii::app()->currency->active->symbol; ?> </div> <div style="clear:both;"></div> <div class="quantity"> <?php echo CHtml::numberField("quantities[{$index}]", $product['quantity'], array('class' => 'count', 'placeholder' => '1')); ?> </div> <div class="actions"> <?php echo CHtml::hiddenField('product_id', $model->id);
/** * @param $limit * @return array */ protected function getNewest($limit) { return StoreProduct::model()->active()->newest()->findAll(array('limit' => $limit)); }
/** * Create/update product from key=>value array * @param $data array of product attributes */ protected function importRow($data) { if (!isset($data['category']) || empty($data['category'])) { $data['category'] = 'root'; } $newProduct = false; $category_id = $this->getCategoryByPath($data['category']); // Search product by name, category // or create new one $cr = new CDbCriteria(); $cr->with = array('translate'); if (isset($data['url']) && !empty($data['url']) && $data['url'] != '') { $cr->compare('t.url', $data['url']); } if (isset($data['sku']) && !empty($data['sku']) && $data['sku'] != '') { $cr->compare('t.sku', $data['sku']); } else { $cr->compare('translate.name', $data['name']); } $model = StoreProduct::model()->applyCategories($category_id)->find($cr); if (!$model) { $newProduct = true; $model = new StoreProduct(); $this->stats['created']++; } else { $this->stats['updated']++; } // Process product type $model->type_id = $this->getTypeIdByName($data['type']); // Manufacturer if (isset($data['manufacturer']) && !empty($data['manufacturer'])) { $model->manufacturer_id = $this->getManufacturerIdByName($data['manufacturer']); } // Update product variables and eav attributes. $attributes = new CsvAttributesProcessor($model, $data); if ($model->validate()) { $categories = array($category_id); if (isset($data['additionalCategories'])) { $categories = array_merge($categories, $this->getAdditionalCategories($data['additionalCategories'])); } if (!$newProduct) { foreach ($model->categorization as $c) { $categories[] = $c->category; } $categories = array_unique($categories); } // Save product $model->save(); // Update EAV data $attributes->save(); // Update categories $model->setCategories($categories, $category_id); // Process product main image if product doesn't have one if (isset($data['image']) && !empty($data['image'])) { $image = CsvImage::create($data['image']); if ($image && $model->mainImage === null) { $model->addImage($image); } if ($image && $this->deleteDownloadedImages) { $image->deleteTempFile(); } } } else { $errors = $model->getErrors(); $error = array_shift($errors); $this->errors[] = array('line' => $this->line, 'error ' => $error[0]); } }
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model = StoreProduct::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $model; }
/** * Count total price */ public function getTotalPrice() { $result = 0; $data = $this->getDataWithModels(); foreach ($data as $item) { $configurable = isset($item['configurable_model']) ? $item['configurable_model'] : 0; $result += StoreProduct::calculatePrices($item['model'], $item['variants'], $configurable) * $item['quantity']; } return $result; }
/** * @param array $products */ public function renderProducts(array $products) { foreach ($products as $p) { if (!count($p->variants)) { $this->renderOffer($p, array('url' => Yii::app()->createAbsoluteUrl('/store/frontProduct/view', array('url' => $p->url)), 'price' => Yii::app()->currency->convert($p->price, $this->_config['currency_id']), 'currencyId' => $this->currencyIso, 'categoryId' => $p->mainCategory->id, 'picture' => $p->mainImage ? Yii::app()->createAbsoluteUrl($p->mainImage->getUrl()) : null, 'name' => CHtml::encode($p->name), 'description' => $this->clearText($p->short_description))); } else { foreach ($p->variants as $v) { $name = strtr('{product}({attr} {option})', array('{product}' => $p->name, '{attr}' => $v->attribute->title, '{option}' => $v->option->value)); $hashtag = '#' . $v->attribute->name . ':' . $v->option->id; $this->renderOffer($p, array('url' => Yii::app()->createAbsoluteUrl('/store/frontProduct/view', array('url' => $p->url)) . $hashtag, 'price' => Yii::app()->currency->convert(StoreProduct::calculatePrices($p, $p->variants, 0), $this->_config['currency_id']), 'currencyId' => $this->currencyIso, 'categoryId' => $p->mainCategory->id, 'picture' => $p->mainImage ? Yii::app()->createAbsoluteUrl($p->mainImage->getUrl()) : null, 'name' => CHtml::encode($name), 'description' => $this->clearText($p->short_description))); } } } }
</td> </tr> <tr align="right"> <td><b><?php echo Yii::t('OrdersModule.admin', 'Сумма товаров'); ?> :</b></td> <td><span id="orderTotalPrice"><?php echo StoreProduct::formatPrice($model->total_price); ?> </span><?php echo Yii::app()->currency->main->symbol; ?> </td> </tr> <tr align="right" style="font-size: 14px;"> <td><b><?php echo Yii::t('OrdersModule.admin', 'К оплате'); ?> :</b></td> <td><span id="orderSummary"><?php echo StoreProduct::formatPrice($model->full_price); ?> </span><?php echo Yii::app()->currency->main->symbol; ?> </td> </tr> </tbody> </table> </div>
</a> </p> <p> <ul> <?php foreach ($order->products as $product) { echo '<li>' . $product->getRenderFullName() . "</li>"; } ?> </ul> <p> <b>Всего к оплате:</b> <?php echo StoreProduct::formatPrice($order->total_price + $order->delivery_price); ?> <?php echo Yii::app()->currency->main->symbol; ?> </p> <p> <b>Контактные данные:</b><br/> <?php echo implode('<br/>', array($order->user_name, $order->user_phone)); ?> </p> </p>
/** * 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 StoreProduct === false) { $product = StoreProduct::model()->findByPk($product); } if ($configuration instanceof StoreProduct === false && $configuration > 0) { $configuration = StoreProduct::model()->findByPk($configuration); } if ($configuration instanceof StoreProduct) { $result = $configuration->price; } else { $result = $product->price; } // if $variants contains not models if (!empty($variants) && $variants[0] instanceof StoreProductVariant === false) { $variants = StoreProductVariant::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; }