Example #1
0
 protected function getProductLinks($id)
 {
     $model = Product::findById($id, null);
     if (is_null($model)) {
         return false;
     }
     $this->frontendLink = Html::a($model->name, ['@product', 'model' => $model, 'category_group_id' => isset($model->category) ? $model->category->category_group_id : null]);
     $this->backendLink = Html::a($model->name, ['/shop/backend-product/edit', 'id' => $model->id, 'returnUrl' => Helper::getReturnUrl()]);
 }
 /**
  * @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;
 }
Example #5
0
 /**
  * @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;
 }
Example #6
0
 /**
  * Product page view
  *
  * @param null $model_id
  * @return string
  * @throws NotFoundHttpException
  * @throws ServerErrorHttpException
  */
 public function actionShow($model_id = null)
 {
     if (null === ($object = Object::getForClass(Product::className()))) {
         throw new ServerErrorHttpException('Object not found.');
     }
     $cacheKey = 'Product:' . $model_id;
     if (false === ($product = Yii::$app->cache->get($cacheKey))) {
         if (null === ($product = Product::findById($model_id))) {
             throw new NotFoundHttpException();
         }
         Yii::$app->cache->set($cacheKey, $product, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getObjectTag(Product::className(), $model_id)]]));
     }
     $request = Yii::$app->request;
     $values_by_property_id = $request->get('properties', []);
     if (!is_array($values_by_property_id)) {
         $values_by_property_id = [$values_by_property_id];
     }
     $selected_category_id = $request->get('last_category_id');
     $selected_category_ids = $request->get('categories', []);
     if (!is_array($selected_category_ids)) {
         $selected_category_ids = [$selected_category_ids];
     }
     $category_group_id = intval($request->get('category_group_id', 0));
     // trigger that we are to show product to user!
     // wow! such product! very events!
     $specialEvent = new ProductPageShowed(['product_id' => $product->id]);
     EventTriggeringHelper::triggerSpecialEvent($specialEvent);
     if (!empty($product->meta_description)) {
         $this->view->registerMetaTag(['name' => 'description', 'content' => ContentBlockHelper::compileContentString($product->meta_description, Product::className() . ":{$product->id}:meta_description", new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(ContentBlock::className()), ActiveRecordHelper::getCommonTag(Product::className())]]))], 'meta_description');
     }
     $selected_category = $selected_category_id > 0 ? Category::findById($selected_category_id) : null;
     $this->view->title = $product->title;
     $this->view->blocks['h1'] = $product->h1;
     $this->view->blocks['announce'] = $product->announce;
     $this->view->blocks['content'] = $product->content;
     $this->view->blocks['title'] = $product->title;
     return $this->render($this->computeViewFile($product, 'show'), ['model' => $product, 'category_group_id' => $category_group_id, 'values_by_property_id' => $values_by_property_id, 'selected_category_id' => $selected_category_id, 'selected_category' => $selected_category, 'selected_category_ids' => $selected_category_ids, 'object' => $object, 'breadcrumbs' => $this->buildBreadcrumbsArray($selected_category, $product)]);
 }
Example #7
0
 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)]);
     }
 }
 public function actionAddProduct($orderId, $productId, $parentId = 0)
 {
     $order = $this->findModel($orderId);
     /** @var OrderItem $orderItem */
     $orderItem = OrderItem::findOne(['product_id' => $productId, 'order_id' => $orderId]);
     /** @var Product $product */
     $product = Product::findById($productId);
     if (is_null($orderItem)) {
         $orderItem = new OrderItem();
         $orderItem->attributes = ['parent_id' => $parentId, 'order_id' => $order->id, 'product_id' => $product->id, 'quantity' => $product->measure->nominal, 'price_per_pcs' => PriceHelper::getProductPrice($product, $order, 1, SpecialPriceList::TYPE_CORE)];
     } else {
         $orderItem->quantity++;
     }
     $orderItem->save();
     $order->calculate(true);
     return $this->redirect(['view', 'id' => $orderId]);
 }
Example #9
0
<?php

/**
 * @var $attribute_name string
 * @var $form \yii\widgets\ActiveForm
 * @var $label string
 * @var $model \app\properties\AbstractModel
 * @var $multiple boolean
 * @var $property_id integer
 * @var $property_key string
 * @var $this \yii\web\View
 * @var $values \app\properties\PropertyValue
 */
use app\modules\shop\models\Product;
use yii\helpers\ArrayHelper;
$productIds = ArrayHelper::getColumn($values->values, 'value');
$data = [];
foreach ($values->values as $value) {
    $product = Product::findById($value['value']);
    if (is_object($product)) {
        $data[$product->id] = $product->name;
    }
}
?>

<?php 
echo \app\backend\widgets\Select2Ajax::widget(['initialData' => $data, 'form' => $form, 'model' => $model, 'modelAttribute' => $property_key, 'multiple' => $multiple === 1, 'searchUrl' => '/shop/backend-product/ajax-related-product', 'additional' => ['placeholder' => Yii::t('app', 'Search')]]);
 /**
  * @param $id
  * @throws NotFoundHttpException
  * @throws \yii\db\Exception
  */
 public function actionGenerate($id)
 {
     $post = \Yii::$app->request->post();
     if (!isset($post['GeneratePropertyValue'])) {
         throw new NotFoundHttpException();
     }
     $parent = Product::findById($id, null);
     if ($parent === null) {
         throw new NotFoundHttpException();
     }
     $object = Object::getForClass(Product::className());
     $catIds = (new Query())->select('category_id')->from([$object->categories_table_name])->where('object_model_id = :id', [':id' => $id])->orderBy(['sort_order' => SORT_ASC, 'id' => SORT_ASC])->column();
     if (isset($post['GeneratePropertyValue'])) {
         $generateValues = $post['GeneratePropertyValue'];
         $post[HasProperties::FIELD_ADD_PROPERTY_GROUP]['Product'] = $post['PropertyGroup']['id'];
     } else {
         $generateValues = [];
     }
     $parent->option_generate = Json::encode(['group' => $post['PropertyGroup']['id'], 'values' => $generateValues]);
     $parent->save();
     $postProperty = [];
     foreach ($post['GeneratePropertyValue'] as $key_property => $values) {
         $inner = [];
         foreach ($values as $key_value => $trash) {
             $inner[] = [$key_property => $key_value];
         }
         $postProperty[] = $inner;
     }
     $optionProperty = self::generateOptions($postProperty);
     foreach ($optionProperty as $option) {
         /** @var Product|HasProperties $model */
         $model = new Product();
         $model->load($post);
         $model->parent_id = $parent->id;
         $nameAppend = [];
         $slugAppend = [];
         $tempPost = [];
         // @todo something
         foreach ($option as $optionValue) {
             foreach ($optionValue as $propertyKey => $propertyValue) {
                 if (!isset($valueModels[$propertyKey])) {
                     $propertyStaticValues = PropertyStaticValues::findOne($propertyValue);
                     $propertyValue = PropertyStaticValues::findById($propertyValue);
                     $key = $propertyStaticValues->property->key;
                     $tempPost[$key] = $propertyValue;
                 }
                 $nameAppend[] = $propertyValue['name'];
                 $slugAppend[] = $propertyValue['id'];
             }
         }
         $model->measure_id = $parent->measure_id;
         $model->name = $parent->name . ' (' . implode(', ', $nameAppend) . ')';
         $model->slug = $parent->slug . '-' . implode('-', $slugAppend);
         $save_model = $model->save();
         $postPropertyKey = 'Properties_Product_' . $model->id;
         $post[$postPropertyKey] = $tempPost;
         if ($save_model) {
             foreach (array_keys($parent->propertyGroups) as $key) {
                 $opg = new ObjectPropertyGroup();
                 $opg->attributes = ['object_id' => $parent->object->id, 'object_model_id' => $model->id, 'property_group_id' => $key];
                 $opg->save();
             }
             $model->saveProperties(['Properties_Product_' . $model->id => $parent->abstractModel->attributes]);
             $model->saveProperties($post);
             unset($post[$postPropertyKey]);
             $add = [];
             foreach ($catIds as $value) {
                 $add[] = [$value, $model->id];
             }
             if (!empty($add)) {
                 Yii::$app->db->createCommand()->batchInsert($object->categories_table_name, ['category_id', 'object_model_id'], $add)->execute();
             }
             $params = $parent->images;
             if (!empty($params)) {
                 $rows = [];
                 foreach ($params as $param) {
                     $rows[] = [$param['object_id'], $model->id, $param['filename'], $param['image_title'], $param['image_alt'], $param['sort_order']];
                 }
                 Yii::$app->db->createCommand()->batchInsert(Image::tableName(), ['object_id', 'object_model_id', 'filename', 'image_title', 'image_alt', 'sort_order'], $rows)->execute();
             }
         }
     }
 }
Example #11
0
 /**
  * renders url according to given data
  * @param $chunkData
  * @param TagDependency $dependency
  * @return string
  */
 private static function renderUrl($chunkData, &$dependency)
 {
     $expression = '%(?P<objectName>[^#]+?)#(?P<objectId>[\\d]+?)$%';
     $output = '';
     preg_match($expression, $chunkData['key'], $m);
     if (true === isset($m['objectName'], $m['objectId'])) {
         $id = (int) $m['objectId'];
         switch (strtolower($m['objectName'])) {
             case "page":
                 if (null !== ($model = Page::findById($id))) {
                     $dependency->tags[] = ActiveRecordHelper::getCommonTag(Page::className());
                     $dependency->tags[] = $model->objectTag();
                     $output = Url::to(['@article', 'id' => $id]);
                 }
                 break;
             case "category":
                 if (null !== ($model = Category::findById($id))) {
                     $dependency->tags[] = ActiveRecordHelper::getCommonTag(Category::className());
                     $dependency->tags[] = $model->objectTag();
                     $output = Url::to(['@category', 'last_category_id' => $id, 'category_group_id' => $model->category_group_id]);
                 }
                 break;
             case "product":
                 if (null !== ($model = app\modules\shop\models\Product::findById($id))) {
                     $dependency->tags[] = ActiveRecordHelper::getCommonTag(Product::className());
                     $dependency->tags[] = $model->objectTag();
                     $output = Url::to(['@product', 'model' => $model, 'category_group_id' => $model->getMainCategory()->category_group_id]);
                 }
                 break;
         }
     }
     return $output;
 }
Example #12
0
 /**
  * Returns instance of OrderItem entity - product or addon
  * Used for calculating prices, etc.
  * @return Product|Addon
  */
 public function sellingItem()
 {
     if ($this->addon_id !== 0) {
         return Addon::findById($this->addon_id);
     } else {
         return Product::findById($this->product_id);
     }
 }
Example #13
0
 * @var $model \app\properties\AbstractModel
 * @var $multiple boolean
 * @var $property_id integer
 * @var $property_key string
 * @var $this \yii\web\View
 * @var $values \app\properties\PropertyValue
 */
use app\models\Property;
use app\modules\shop\models\Product;
use yii\helpers\ArrayHelper;
use kartik\helpers\Html;
$productIds = ArrayHelper::getColumn($values->values, 'value');
/** @var Product[] $products */
$products = [];
foreach ($productIds as $id) {
    $product = Product::findById($id);
    if ($product !== null) {
        $products[] = $product;
    }
}
?>

<dl>
    <?php 
if (count($products) == 0) {
    return;
}
$property = Property::findById($property_id);
echo Html::tag('dt', $property->name);
foreach ($products as $product) {
    echo Html::tag('dd', Html::a($product->name, ['@product', 'model' => $product]));
Example #14
0
echo \app\backend\components\Helper::saveButtons($model);
$this->endBlock();
?>


<section id="widget-grid">
    <div class="row">

        <article class="col-xs-12 col-sm-6 col-md-6 col-lg-6">

            <?php 
BackendWidget::begin(['title' => Yii::t('app', 'Addon'), 'icon' => 'cart-plus', 'footer' => $this->blocks['submit']]);
?>

            <?php 
echo \app\backend\widgets\Select2Ajax::widget(['initialData' => $model->is_product_id > 0 ? [$model->is_product_id => \app\modules\shop\models\Product::findById($model->is_product_id)->name] : [], 'form' => $form, 'model' => $model, 'modelAttribute' => 'is_product_id', 'multiple' => false, 'searchUrl' => '/shop/backend-product/ajax-related-product', 'additional' => ['placeholder' => 'Поиск продуктов ...']]);
?>

            <?php 
echo $form->field($model, 'name');
?>

            <?php 
echo $form->field($model, 'price', ['addon' => ['append' => ['content' => Html::activeDropDownList($model, 'currency_id', app\modules\shop\models\Currency::getSelection())]]]);
?>

            <?php 
echo $form->field($model, 'price_is_multiplier')->widget(\kartik\switchinput\SwitchInput::className());
?>

            <?php 
</th>
            <td>
                <?php 
echo isset($review->author_phone) ? $review->author_phone : Html::tag('em', Yii::t('yii', '(not set)'));
?>

            </td>
        </tr>
        <tr>
            <th style="text-align: left;"><?php 
echo $review->getAttributeLabel('text');
?>
</th>
            <td>
                <?php 
echo isset($review->text) ? $review->text : Html::tag('em', Yii::t('yii', '(not set)'));
?>
            </td>
        </tr>
        <?php 
$row = '';
$obj = Product::findById($review->object_model_id);
if ($obj !== null) {
    $row = Html::tag('tr', Html::tag('th', 'Продукт', ['style' => 'text-align: left;']) . Html::tag('td', Html::a($obj->name, Url::to(['/shop/product/show', 'model' => $obj], true))), ['style' => 'background: #f5f5f5;']);
}
$output = Html::tag('p', 'See review details ' . Html::a('here', Url::to(['/backend/review/products'], true)));
echo $row;
?>
    </table>
<?php 
echo $output;
Example #16
0
 /**
  * @param Order $order
  * @param array $products
  * @param $result
  * @param int $parentId
  * @return mixed
  * @throws BadRequestHttpException
  * @throws NotFoundHttpException
  */
 protected function addProductsToOrder(Order $order, $products = [], $result, $parentId = 0)
 {
     $parentId = intval($parentId);
     if ($parentId !== 0) {
         // if parent id is set - order item should exist in this order!
         $parentOrderItem = OrderItem::findOne(['order_id' => $order->id, 'id' => $parentId]);
         if ($parentOrderItem === null) {
             throw new BadRequestHttpException();
         }
     }
     foreach ($products as $product) {
         $productModel = $addonModel = null;
         if (!isset($product['id'])) {
             if (isset($product['addon_id'])) {
                 $addonModel = Addon::findById($product['addon_id']);
             }
         } else {
             $productModel = Product::findById($product['id']);
         }
         if ($addonModel === null && $productModel === null) {
             $result['errors'][] = Yii::t('app', 'Product not found.');
             continue;
         }
         /** @var Product $productModel */
         $quantity = isset($product['quantity']) && (double) $product['quantity'] > 0 ? (double) $product['quantity'] : 1;
         $condition = ['order_id' => $order->id, 'parent_id' => 0];
         if ($productModel !== null) {
             $condition['product_id'] = $productModel->id;
             $thisItemModel = $productModel;
             $quantity = $productModel->measure->ceilQuantity($quantity);
         } else {
             $condition['addon_id'] = $addonModel->id;
             $thisItemModel = $addonModel;
             if (!$addonModel->can_change_quantity) {
                 $quantity = 1;
             }
         }
         $orderItem = OrderItem::findOne($condition);
         if ($this->module->allowToAddSameProduct || null === $orderItem) {
             $orderItem = new OrderItem();
             $orderItem->attributes = ['parent_id' => $parentId, 'order_id' => $order->id, 'quantity' => $quantity, 'price_per_pcs' => PriceHelper::getProductPrice($thisItemModel, $order, 1, SpecialPriceList::TYPE_CORE)];
             if (empty($product['customName']) === false) {
                 $orderItem->custom_name = $product['customName'];
             }
             if ($productModel !== null) {
                 $orderItem->product_id = $thisItemModel->id;
             } else {
                 $orderItem->addon_id = $thisItemModel->id;
             }
         } else {
             /** @var OrderItem $orderItem */
             if ($addonModel !== null && !$addonModel->can_change_quantity) {
                 // quantity can not be changed
                 $quantity = 0;
             }
             if (null !== $orderItem) {
                 $orderItem->quantity += $quantity;
             }
         }
         if (false === $orderItem->save()) {
             $result['errors'][] = Yii::t('app', 'Cannot save order item.');
         } else {
             // refresh order
             Order::clearStaticOrder();
             $order = $this->loadOrder(false);
         }
         if (null !== $productModel) {
             $result['products'][] = ['model' => $productModel, 'quantity' => $quantity, 'orderItem' => $orderItem];
         }
         if (isset($product['children']) && is_array($product['children'])) {
             $result = $this->addProductsToOrder($order, $product['children'], $result, $orderItem->id);
         }
     }
     return $result;
 }