public function down() { $this->dropColumn(Category::tableName(), 'date_added'); $this->dropColumn(Category::tableName(), 'date_modified'); $this->dropColumn(Product::tableName(), 'date_added'); $this->dropColumn(Product::tableName(), 'date_modified'); }
protected function getLinks() { if (!is_null($this->frontendLink) || !is_null($this->backendLink)) { return true; } /** @var Image $image */ $image = Image::findById($this->img_id); if (is_null($image) || is_null($object = Object::findById($image->object_id))) { return false; } /** @var \app\models\Object $object */ switch ($object->object_class) { case Page::className(): $this->getPageLinks($image->object_model_id); break; case Category::className(): $this->getCategoryLinks($image->object_model_id); break; case Product::className(): $this->getProductLinks($image->object_model_id); break; default: return false; } return true; }
public function actionEdit($id = null) { $model = new PrefilteredPages(); $model->loadDefaultValues(); if ($id !== null) { $model = PrefilteredPages::findOne($id); } $static_values_properties = []; $property_groups_ids_for_object = (new Query())->select('id')->from(PropertyGroup::tableName())->where(['object_id' => Object::getForClass(Product::className())->id])->column(); $properties = Property::find()->andWhere(['in', 'property_group_id', $property_groups_ids_for_object])->all(); foreach ($properties as $prop) { /** @var Property $prop */ $static_values_properties[$prop->id] = ['property' => $prop, 'static_values_select' => PropertyStaticValues::getSelectForPropertyId($prop->id), 'has_static_values' => $prop->has_static_values === 1]; } $post = \Yii::$app->request->post(); if ($model->load($post) && $model->validate()) { $save_result = $model->save(); if ($save_result) { Yii::$app->session->setFlash('info', Yii::t('app', 'Object saved')); $returnUrl = Yii::$app->request->get('returnUrl', ['index', 'id' => $model->id]); switch (Yii::$app->request->post('action', 'save')) { case 'next': return $this->redirect(['edit', 'returnUrl' => $returnUrl]); case 'back': return $this->redirect($returnUrl); default: return $this->redirect(Url::toRoute(['edit', 'id' => $model->id, 'returnUrl' => $returnUrl])); } //return $this->redirect(['/backend/prefiltered-pages/edit', 'id' => $model->id]); } else { \Yii::$app->session->setFlash('error', Yii::t('app', 'Cannot update data')); } } return $this->render('prefiltered-page-form', ['model' => $model, 'static_values_properties' => $static_values_properties]); }
/** * @return string */ public function actionPrint() { $this->layout = 'print'; $products = ProductCompareHelper::getProductsList(true); $object = Object::getForClass(Product::className()); return $this->render('print', ['error' => empty($products) || null === $object, 'message' => Yii::t('app', 'No products for comparing'), 'object' => $object, 'products' => $products]); }
/** * @return string */ public function run() { parent::run(); if (null === $this->rootCategory) { return ''; } $cacheKey = $this->className() . ':' . implode('_', [$this->viewFile, $this->rootCategory, null === $this->depth ? 'null' : intval($this->depth), intval($this->includeRoot), intval($this->fetchModels), intval($this->onlyNonEmpty), implode(',', $this->excludedCategories), \Yii::$app->request->url]) . ':' . json_encode($this->additional); if (false !== ($cache = \Yii::$app->cache->get($cacheKey))) { return $cache; } /** @var array|Category[] $tree */ $tree = Category::getMenuItems(intval($this->rootCategory), $this->depth, boolval($this->fetchModels)); if (true === $this->includeRoot) { if (null !== ($_root = Category::findById(intval($this->rootCategory)))) { $tree = [['label' => $_root->name, 'url' => Url::toRoute(['@category', 'category_group_id' => $_root->category_group_id, 'last_category_id' => $_root->id]), 'id' => $_root->id, 'model' => $this->fetchModels ? $_root : null, 'items' => $tree]]; } } if (true === $this->onlyNonEmpty) { $_sq1 = (new Query())->select('main_category_id')->distinct()->from(Product::tableName()); $_sq2 = (new Query())->select('category_id')->distinct()->from('{{%product_category}}'); $_query = (new Query())->select('id')->from(Category::tableName())->andWhere(['not in', 'id', $_sq1])->andWhere(['not in', 'id', $_sq2])->all(); $this->excludedCategories = array_merge($this->excludedCategories, array_column($_query, 'id')); } $tree = $this->filterTree($tree); $cache = $this->render($this->viewFile, ['tree' => $tree, 'fetchModels' => $this->fetchModels, 'additional' => $this->additional, 'activeClass' => $this->activeClass, 'activateParents' => $this->activateParents]); \Yii::$app->cache->set($cacheKey, $cache, 0, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(Category::className()), ActiveRecordHelper::getCommonTag(Product::className())]])); return $cache; }
public function up() { $this->addColumn(Page::tableName(), 'mate_keywords', $this->string()->defaultValue(null)); $this->addColumn(Product::tableName(), 'mate_keywords', $this->string()->defaultValue(null)); $this->addColumn(Category::tableName(), 'mate_keywords', $this->string()->defaultValue(null)); $this->addColumn(PrefilteredPages::tableName(), 'mate_keywords', $this->string()->defaultValue(null)); }
protected function productsSitemap($categoryId, $categoryUrl) { $product = Product::find()->select(['id', 'slug'])->where(['main_category_id' => $categoryId, 'active' => 1])->asArray(true)->all(); array_reduce($product, function ($carry, $item) use($categoryUrl) { $this->sitemap->addUrl($categoryUrl . '/' . $item['slug']); }); }
public function actionIndex($category_id = null) { $searchModel = new Category(); $searchModel->active = 1; $params = Yii::$app->request->get(); $dataProvider = $searchModel->search($params); $selectedCategory = null; if ($category_id !== null) { $selectedCategory = Category::findById($category_id); } if ($selectedCategory !== null) { if (Yii::$app->request->isPost === true) { $newProperty = isset($_GET['add_property_id']) ? Property::findById($_GET['add_property_id']) : null; if ($newProperty !== null) { $filterSet = new FilterSets(); $filterSet->category_id = $selectedCategory->id; $filterSet->property_id = $newProperty->id; $filterSet->sort_order = 65535; $filterSet->save(); } } } $groups = PropertyGroup::getForObjectId(Object::getForClass(Product::className())->id, false); $propertiesDropdownItems = []; foreach ($groups as $group) { $item = ['label' => $group->name, 'url' => '#', 'items' => []]; $properties = Property::getForGroupId($group->id); foreach ($properties as $prop) { $item['items'][] = ['label' => $prop->name, 'url' => '?category_id=' . $category_id . '&add_property_id=' . $prop->id, 'linkOptions' => ['class' => 'add-property-to-filter-set', 'data-property-id' => $prop->id, 'data-action' => 'post']]; } $propertiesDropdownItems[] = $item; } return $this->render('index', ['dataProvider' => $dataProvider, 'searchModel' => $searchModel, 'selectedCategory' => $selectedCategory, 'propertiesDropdownItems' => $propertiesDropdownItems]); }
/** * @inheritdoc * @return string * @throws InvalidConfigException * @throws \yii\web\ServerErrorHttpException */ public function run() { parent::run(); if (null === $this->category_group_id) { throw new InvalidConfigException("ProductsWidget.category_group_id should be set"); } $products = Product::filteredProducts($this->category_group_id, $this->values_by_property_id, $this->selected_category_id, $this->force_sorting, $this->limit, false, $this->force_limit, $this->additional_filters); return $this->render($this->viewFile, ['products' => $products, 'itemView' => $this->itemView, 'values_by_property_id' => $this->values_by_property_id, 'category_group_id' => $this->category_group_id, 'selected_category_id' => $this->selected_category_id]); }
public static function editQuery(SearchEvent $event) { /** @var \app\modules\shop\ShopModule $module */ $module = \Yii::$app->modules['shop']; $event->activeQuery->select('`id`')->from(Product::tableName())->orWhere('`name` LIKE :q')->orWhere('`h1` LIKE :q')->orWhere('`content` LIKE :q')->orWhere('`sku` LIKE :q')->addParams([':q' => '%' . $event->q . '%'])->andWhere(['active' => 1]); if ($module->allowSearchGeneratedProducts != 1) { $event->activeQuery->andWhere(['parent_id' => 0]); } }
public function searchProductsByDescription() { /** @var \app\modules\shop\ShopModule $module */ $module = Yii::$app->modules['shop']; $query = (new Query())->select('`id`')->from(Product::tableName())->orWhere('`name` LIKE :q')->orWhere('`h1` LIKE :q')->orWhere('`content` LIKE :q')->orWhere('`sku` LIKE :q')->addParams([':q' => '%' . $this->q . '%'])->andWhere(['active' => 1]); if ($module->allowSearchGeneratedProducts != 1) { $query->andWhere(['parent_id' => 0]); } return ArrayHelper::getColumn($query->all(), 'id'); }
public function down() { $this->dropTable('{{%special_price_list_type}}'); $this->dropTable('{{%special_price_object}}'); $this->dropColumn('{{%special_price_list}}', 'type_id'); $this->addColumn('{{%special_price_list}}', 'type', "ENUM('core', 'discount', 'delivery', 'project') DEFAULT 'project'"); $this->update('{{%special_price_list}}', ['type' => 'core'], ['class' => 'app\\modules\\shop\\models\\Currency', 'object_id' => Object::getForClass(Product::className())->id]); $this->update('{{%special_price_list}}', ['type' => 'discount'], ['class' => 'app\\modules\\shop\\models\\Discount', 'object_id' => Object::getForClass(Product::className())->id]); $this->delete('{{%special_price_list}}', ['class' => 'app\\modules\\shop\\models\\Discount', 'object_id' => Object::getForClass(Order::className())->id]); }
public function up() { // return false; $this->addColumn('{{%special_price_list}}', 'handler', Schema::TYPE_STRING); $this->update('{{%special_price_list}}', ['class' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'handler' => 'getCurrencyPriceProduct'], ['class' => 'app\\modules\\shop\\models\\Currency', 'object_id' => \app\models\Object::getForClass(\app\modules\shop\models\Product::className())->id]); $this->update('{{%special_price_list}}', ['class' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'handler' => 'getDiscountPriceProduct'], ['class' => 'app\\modules\\shop\\models\\Discount', 'object_id' => \app\models\Object::getForClass(\app\modules\shop\models\Product::className())->id]); $this->update('{{%special_price_list}}', ['class' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'handler' => 'getDiscountPriceOrder'], ['class' => 'app\\modules\\shop\\models\\Discount', 'object_id' => \app\models\Object::getForClass(\app\modules\shop\models\Order::className())->id]); $this->insert('{{%special_price_list}}', ['object_id' => \app\models\Object::getForClass(\app\modules\shop\models\Order::className())->id, 'class' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'active' => 1, 'sort_order' => 12, 'handler' => 'getDeliveryPriceOrder', 'type_id' => (new \yii\db\Query())->select('id')->from('{{%special_price_list_type}}')->where(['key' => 'delivery'])->scalar()]); $this->insert('{{%events}}', ['owner_class_name' => 'app\\modules\\shop\\ShopModule', 'event_name' => 'order_calculate', 'event_class_name' => 'app\\modules\\shop\\events\\OrderCalculateEvent', 'selector_prefix' => '', 'event_description' => '', 'documentation_link' => '']); $eventId = $this->db->lastInsertID; $this->insert('{{%event_handlers}}', ['event_id' => $eventId, 'sort_order' => 0, 'handler_class_name' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'handler_function_name' => 'handleSaveDiscounts', 'is_active' => 1, 'non_deletable' => 0, 'triggering_type' => 'application_trigger']); }
public function search($params) { $query = Product::find()->with('prices'); $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => new \yii\data\Sort(['attributes' => ['name', 'id', 'available']])]); $this->load($params); if (!$this->validate()) { return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'category_id' => $this->category_id, 'available' => $this->available, 'producer_id' => $this->producer_id]); $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'text', $this->text])->andFilterWhere(['like', 'code', $this->code])->andFilterWhere(['like', 'short_text', $this->short_text])->andFilterWhere(['like', 'category_id', $this->category_id]); return $dataProvider; }
public function getData() { if ($this->data === []) { $event = new ModificationDataEvent(); $query = Product::find()->where(['active' => 1]); foreach ($query->each() as $product) { $event->model = $product; $this->trigger(self::MODIFICATION_DATA, $event); $this->data[] = $event->dataArray; } } return $this->data; }
/** * @return string */ public function run() { parent::run(); if (!$this->product instanceof Product) { return ''; } $cacheKey = 'RelatedProduct:' . implode('_', [$this->viewFile, $this->product, json_encode($this->additional)]); if (false !== ($cache = \Yii::$app->cache->get($cacheKey))) { return $cache; } $result = $this->render($this->viewFile, ['model' => $this->product, 'products' => $this->product->relatedProducts, 'additional' => $this->additional]); \Yii::$app->cache->set($cacheKey, $result, 0, new TagDependency(['tags' => [ActiveRecordHelper::getObjectTag(Product::className(), $this->product->id), ActiveRecordHelper::getCommonTag(\app\modules\shop\models\RelatedProduct::className())]])); return $result; }
public function run() { app\backend\assets\FrontendEditingAsset::register($this->view); $items = [['label' => Icon::show('dashboard') . ' ' . Yii::t('app', 'Backend'), 'url' => ['/backend/']]]; switch (Yii::$app->requestedRoute) { case 'shop/product/list': if (isset($_GET['properties'])) { $apply_if_params = []; foreach ($_GET['properties'] as $property_id => $values) { if (isset($values[0])) { $apply_if_params[$property_id] = $values[0]; } } if (Yii::$app->response->dynamic_content_trait === true) { $items[] = ['label' => Icon::show('puzzle') . ' ' . Yii::t('app', 'Edit Dynamic Content'), 'url' => ['/backend/dynamic-content/edit', 'id' => Yii::$app->response->matched_dynamic_content_trait_model->id]]; } else { if (isset($_GET['properties'], $_GET['last_category_id'])) { $items[] = ['label' => Icon::show('puzzle') . ' ' . Yii::t('app', 'Add Dynamic Content'), 'url' => ['/backend/dynamic-content/edit', 'DynamicContent' => ['apply_if_params' => Json::encode($apply_if_params), 'apply_if_last_category_id' => $_GET['last_category_id'], 'object_id' => Object::getForClass(app\modules\shop\models\Product::className())->id, 'route' => 'shop/product/list']]]; } } } else { // no properties selected - go to category edit page if (isset($_GET['last_category_id'])) { $reviewsLink = $this->getReviewEditParams("Category", intval($_GET['last_category_id'])); $cat = app\modules\shop\models\Category::findById($_GET['last_category_id']); $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit category'), 'url' => ['/shop/backend-category/edit', 'id' => $cat->id, 'parent_id' => $cat->parent_id]]; } } break; case 'shop/product/show': if (isset($_GET['model_id'])) { $reviewsLink = $this->getReviewEditParams("Product", intval($_GET['model_id'])); $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit product'), 'url' => ['/shop/backend-product/edit', 'id' => intval($_GET['model_id'])]]; } break; case '/page/page/show': case '/page/page/list': if (isset($_GET['id'])) { $page = app\modules\page\models\Page::findById($_GET['id']); $reviewsLink = $this->getReviewEditParams("Page", $_GET['id']); $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit page'), 'url' => ['/page/backend/edit', 'id' => $page->id, 'parent_id' => $page->parent_id]]; } break; } if (!empty($reviewsLink)) { $items[] = $reviewsLink; } return $this->render('floating-panel', ['items' => $items, 'bottom' => $this->bottom]); }
public static function editQuery(SearchEvent $event) { /** @var \app\modules\shop\ShopModule $module */ $module = \Yii::$app->modules['shop']; /** @var \app\modules\shop\ShopModule $module */ $properties = (new Query())->select('`id`')->from(PropertyStaticValues::tableName())->where('`name` LIKE :q')->addParams([':q' => '%' . $event->q . '%'])->all(); $event->activeQuery->select('{{%object_static_values}}.object_model_id')->distinct(true)->from(ObjectStaticValues::tableName())->where('{{%object_static_values}}.object_id = :objectId')->addParams([':objectId' => Object::getForClass(Product::className())->id])->andWhere(['in', '{{%object_static_values}}.property_static_value_id', ArrayHelper::getColumn($properties, 'id')]); if ($module->allowSearchGeneratedProducts != 1) { $event->activeQuery->innerJoin('{{%product}}', '{{%product}}.id = {{%object_static_values}}.object_model_id'); $event->activeQuery->andWhere(['{{%product}}.parent_id' => 0, '{{%product}}.active' => 1]); } $event->setFunctionSearch(function ($activeQuery) { return ArrayHelper::getColumn($activeQuery->all(), 'object_model_id'); }); }
/** * @param $term * @return string JSON */ public function actionAutoCompleteSearch($term) { Yii::$app->response->format = Response::FORMAT_JSON; $query = Product::find()->select(['id', 'name', 'main_category_id', 'slug', 'sku'])->orderBy(['sort_order' => SORT_ASC, 'id' => SORT_DESC]); foreach (['name', 'content', 'sku'] as $attribute) { $query->orWhere(['like', $attribute, $term]); } $query->andWhere(['active' => 1]); $products = $query->limit(Yii::$app->getModule('core')->autoCompleteResultsCount)->all(); $result = []; foreach ($products as $product) { /** @var Product $product */ $result[] = ['id' => $product->id, 'name' => $product->name, 'url' => Url::toRoute(['@product', 'model' => $product, 'category_group_id' => $product->getMainCategory()->category_group_id], true)]; } return $result; }
/** * @param ActiveQuery $query * @return ActiveQuery */ public function filter(ActiveQuery $query, &$cacheKeyAppend) { $get = Yii::$app->request->get(); $params = array_merge($get, Yii::$app->request->post()); $min = floatval(ArrayHelper::getValue($params, $this->minAttribute, $this->minValue)); $max = floatval(ArrayHelper::getValue($params, $this->maxAttribute, $this->maxValue)); if ($min !== floatval($this->minValue)) { $cacheKeyAppend .= "[MinPrice:{$min}]"; $query = $query->andWhere(Product::tableName() . '.price >= :min_price', [':min_price' => $min]); $get[$this->minAttribute] = $min; } if ($max !== floatval($this->maxValue) && (double) 0 !== floatval($max)) { $cacheKeyAppend .= "[MaxPrice:{$max}]"; $query = $query->andWhere(Product::tableName() . '.price <= :max_price', [':max_price' => $max]); $get[$this->maxAttribute] = $max; } Yii::$app->request->setQueryParams($get); return $query; }
/** * @param $term * @return string JSON */ public function actionAutoCompleteSearch($term) { Yii::$app->response->format = Response::FORMAT_JSON; $search = new Search(); $search->q = $term; $search->on(Search::QUERY_SEARCH_PRODUCTS_BY_DESCRIPTION, function (SearchEvent $event) { $event->setFunctionSearch(function ($activeQuery) { $activeQuery->limit(Yii::$app->getModule('core')->autoCompleteResultsCount); return Product::find()->select(['id', 'name', 'main_category_id', 'slug', 'sku'])->where(['id' => $activeQuery->all()])->all(); }); }); $products = $search->searchProductsByDescription(); $result = []; foreach ($products as $product) { /** @var Product $product */ $result[] = ['id' => $product->id, 'name' => $product->name, 'url' => Url::toRoute(['@product', 'model' => $product, 'category_group_id' => $product->getMainCategory()->category_group_id], true)]; } return $result; }
/** * @inheritdoc * @return string */ public function run() { parent::run(); if (!Yii::$app->session->has('lastViewedProdsList')) { return "<!-- Can't render - session is not contains a products -->"; } $productsInSession = Yii::$app->session->get('lastViewedProdsList'); if (is_array(!$productsInSession)) { return "<!-- Can't render - session is not contains a products array -->"; } $products = []; foreach ($productsInSession as $elem) { $prod = Product::findById($elem['product_id']); if (null !== $prod) { $products[] = $prod; } } return $this->render('lastviewedproducts\\main-view', ['title' => $this->title, 'elementNumber' => $this->elementNumber, 'products' => $products]); }
protected function addProductsToOrder($products, $parentId = 0) { if (!is_array($products)) { throw new BadRequestHttpException(); } $order = $this->loadOrder(true); $result = ['errors' => [], 'itemModalPreview' => '']; foreach ($products as $product) { if (!isset($product['id']) || is_null($productModel = Product::findById($product['id']))) { $result['errors'][] = Yii::t('app', 'Product not found.'); continue; } /** @var Product $productModel */ $quantity = isset($product['quantity']) && (double) $product['quantity'] > 0 ? (double) $product['quantity'] : 1; $quantity = $productModel->measure->ceilQuantity($quantity); if ($this->module->allowToAddSameProduct || is_null($orderItem = OrderItem::findOne(['order_id' => $order->id, 'product_id' => $productModel->id, 'parent_id' => 0]))) { $orderItem = new OrderItem(); $orderItem->attributes = ['parent_id' => $parentId, 'order_id' => $order->id, 'product_id' => $productModel->id, 'quantity' => $quantity, 'price_per_pcs' => PriceHelper::getProductPrice($productModel, $order, 1, SpecialPriceList::TYPE_CORE)]; } else { /** @var OrderItem $orderItem */ $orderItem->quantity += $quantity; } if (!$orderItem->save()) { $result['errors'][] = Yii::t('app', 'Cannot save order item.'); } else { // refresh order Order::clearStaticOrder(); $order = $this->loadOrder(false); } if (isset($product['children'])) { $result = ArrayHelper::merge($result, $this->addProductsToOrder($product['children'], $orderItem->id)); } if ($parentId === 0) { $result['itemModalPreview'] .= $this->renderPartial('item-modal-preview', ['order' => $order, 'orderItem' => $orderItem, 'product' => $product]); } } if ($parentId === 0) { $order->calculate(true); } $mainCurrency = Currency::getMainCurrency(); return ArrayHelper::merge($result, ['itemsCount' => $order->items_count, 'success' => true, 'totalPrice' => $mainCurrency->format($order->total_price)]); }
/** * @param int $id * @return bool */ public static function addProductToList($id) { $id = intval($id); if (null === Product::findById($id)) { return false; } $comparisonProductList = static::getProductsList(); if (static::productInList($id, $comparisonProductList)) { return false; } /** @var \app\modules\shop\ShopModule $module */ $module = Yii::$app->modules['shop']; if (count($comparisonProductList) > $module->maxProductsToCompare) { array_shift($comparisonProductList); } $comparisonProductList[$id] = $id; Yii::$app->session->set(static::SESSION_COMPARE_LIST, $comparisonProductList); yii\caching\TagDependency::invalidate(Yii::$app->cache, ['Session:' . Yii::$app->session->id]); return true; }
public function getPossibleSelections() { $allowed_category_ids = []; if ($this->onlyAvailableProducts) { $object = Object::getForClass(Product::className()); if (!is_null($object) && isset($this->current_selections['last_category_id'])) { $cacheKey = 'CategoriesFilterWidget: ' . $object->id . ':' . $this->current_selections['last_category_id'] . ':' . Json::encode($this->current_selections['properties']); $allowed_category_ids = Yii::$app->cache->get($cacheKey); if ($allowed_category_ids === false) { $query = new Query(); $query = $query->select($object->categories_table_name . '.category_id')->distinct()->from($object->categories_table_name); if (count($this->current_selections['properties']) > 0) { foreach ($this->current_selections['properties'] as $property_id => $values) { $joinTableName = 'OSVJoinTable' . $property_id; $query->join('JOIN', ObjectStaticValues::tableName() . ' ' . $joinTableName, $joinTableName . '.object_id = :objectId AND ' . $joinTableName . '.object_model_id = ' . $object->categories_table_name . '.object_model_id ', [':objectId' => $object->id]); $imploded_values = implode(', ', array_map('intval', $values)); $query->andWhere(new Expression('`' . $joinTableName . '`.`property_static_value_id`' . ' in (' . $imploded_values . ')')); } } $allowed_category_ids = $query->column(); Yii::$app->cache->set($cacheKey, $allowed_category_ids, 86400, new \yii\caching\TagDependency(['tags' => [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag($object->object_class), \devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(Category::className())]])); $object = null; } } } $this->possible_selections = []; $models = Category::getByLevel($this->category_group_id); if (isset($models[0]) && $this->omit_root == true) { $models = Category::getByParentId($models[0]->id); } $this->possible_selections = []; foreach ($models as $model) { if ($this->onlyAvailableProducts === true && !in_array($model->id, $allowed_category_ids)) { continue; } $this->possible_selections[] = $this->recursiveGetTree($model, $allowed_category_ids); } return $this->possible_selections; }
/** * @param ActiveQuery $query * @return ActiveQuery */ public function filter(ActiveQuery $query, &$cacheKeyAppend) { $get = array_merge(Yii::$app->request->get(), Yii::$app->request->post()); $isChange = isset($get[$this->changeAttribute]) && $get[$this->changeAttribute] == 1 ? true : false; $min = floatval(ArrayHelper::getValue($get, $this->minAttribute, $this->minValue)); $max = floatval(ArrayHelper::getValue($get, $this->maxAttribute, $this->maxValue)); if ($min !== floatval($this->minValue) && $isChange) { $cacheKeyAppend .= "[MinPrice:{$min}]"; $query = $query->andWhere(Product::tableName() . '.price >= :min_price', [':min_price' => $min]); } else { ArrayHelper::remove($get, $this->minAttribute); ArrayHelper::remove($_GET, $this->minAttribute); Yii::$app->request->setQueryParams($get); } if ($max !== floatval($this->maxValue) && $isChange) { $cacheKeyAppend .= "[MaxPrice:{$max}]"; $query = $query->andWhere(Product::tableName() . '.price <= :max_price', [':max_price' => $max]); } else { ArrayHelper::remove($get, $this->maxAttribute); ArrayHelper::remove($_GET, $this->maxAttribute); Yii::$app->request->setQueryParams($get); } return $query; }
/** * @param int|Product|null $product * @param bool $asMainCategory * @return bool */ public function linkProduct($product = null, $asMainCategory = false) { if ($product instanceof Product) { return $product->linkToCategory($this->id, $asMainCategory); } elseif (is_int($product) || is_string($product)) { $product = intval($product); if (null !== ($product = Product::findById($product, null))) { return $product->linkToCategory($this->id, $asMainCategory); } } return false; }
/** * Search handler * @return array * @throws ForbiddenHttpException */ public function actionSearch() { $headers = Yii::$app->response->getHeaders(); $headers->set('X-Robots-Tag', 'none'); $headers->set('X-Frame-Options', 'SAMEORIGIN'); $headers->set('X-Content-Type-Options', 'nosniff'); if (!Yii::$app->request->isAjax) { throw new ForbiddenHttpException(); } $model = new Search(); $model->load(Yii::$app->request->get()); $cacheKey = 'ProductSearchIds: ' . $model->q; $ids = Yii::$app->cache->get($cacheKey); if ($ids === false) { $ids = ArrayHelper::merge($model->searchProductsByDescription(), $model->searchProductsByProperty()); Yii::$app->cache->set($cacheKey, $ids, 86400, new TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Product::className())])); } /** @var \app\modules\shop\ShopModule $module */ $module = Yii::$app->modules['shop']; $pages = new Pagination(['defaultPageSize' => $module->searchResultsLimit, 'forcePageParam' => false, 'totalCount' => count($ids)]); $cacheKey .= ' : ' . $pages->offset; $products = Yii::$app->cache->get($cacheKey); if ($products === false) { $products = Product::find()->where(['in', '`id`', array_slice($ids, $pages->offset, $pages->limit)])->addOrderBy('sort_order')->with('images')->all(); Yii::$app->cache->set($cacheKey, $products, 86400, new TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Product::className())])); } Yii::$app->response->format = Response::FORMAT_JSON; return ['view' => $this->renderAjax('search', ['model' => $model, 'pages' => $pages, 'products' => $products]), 'totalCount' => count($ids)]; }
/** * @return array */ public function actionAjaxSearch() { Yii::$app->response->format = Response::FORMAT_JSON; $search = \Yii::$app->request->get('search', []); $object = !empty($search['object']) ? intval($search['object']) : 0; $term = !empty($search['term']) ? $search['term'] : ''; $result = ['more' => false, 'results' => []]; if (null === ($object = Object::findById($object))) { return $result; } /** @var ActiveRecord $class */ $class = $object->object_class; $list = [Product::className(), Category::className(), Page::className()]; if (!in_array($class, $list)) { return $result; } $query = $class::find()->select('id, name, "#" `url`')->andWhere(['like', 'name', $term])->asArray(true); $result['results'] = array_values($query->all()); array_walk($result['results'], function (&$val) use($class) { if (null !== ($model = $class::findOne(['id' => $val['id']]))) { if (Product::className() === $model->className()) { $val['url'] = Url::toRoute(['@product', 'model' => $model, 'category_group_id' => $model->category->category_group_id]); } elseif (Category::className() === $model->className()) { $val['url'] = Url::toRoute(['@category', 'last_category_id' => $model->id, 'category_group_id' => $model->category_group_id]); } else { if (Page::className() === $model->className()) { $val['url'] = Url::toRoute(['@article', 'id' => $model->id]); } } } }); return $result; }
public static function renderEcommerceCounters(Event $event) { $order = Order::findOne(['id' => $event->data['orderId']]); $config = Config::getModelByKey('ecommerceCounters'); if (empty($event->data['orderId']) || empty($config) || empty($order)) { return; } $orderItems = OrderItem::findAll(['order_id' => $event->data['orderId']]); if (!empty($orderItems)) { $products = []; foreach ($orderItems as $item) { $product = Product::findById($item->product_id, null, null); if (empty($product)) { continue; } $category = Category::findById($product->main_category_id); $category = empty($category) ? 'Магазин' : str_replace('\'', '', $category->name); $products[] = ['id' => $product->id, 'name' => str_replace('\'', '', $product->name), 'price' => number_format($product->price, 2, '.', ''), 'category' => $category, 'qnt' => $item->quantity]; } $order = ['id' => $order->id, 'total' => number_format($order->total_price, 2, '.', '')]; echo Yii::$app->view->renderFile(Yii::getAlias('@app/modules/seo/views/manage/_ecommerceCounters.php'), ['order' => $order, 'products' => $products, 'config' => Json::decode($config->value)]); } }