Inheritance: extends MultilingualObject
 public function loadModel($id)
 {
     $model = ProductOption::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
Ejemplo n.º 2
0
 public function run()
 {
     $faker = Faker::create();
     foreach (range(1, 25) as $index) {
         $name = $faker->sentence;
         ProductOption::create(['name' => $name, 'key' => Str::slug($name), 'option_group_id' => $faker->numberBetween(1, 10)]);
     }
 }
Ejemplo n.º 3
0
 public function loadProductOption($id)
 {
     $_productoption = array();
     $data = ProductOption::model()->findAll('product_id=:product_id', array(':product_id' => $id));
     if (!empty($data)) {
         foreach ($data as $productoption) {
             $value = ProductOptionValue::model()->findAll('product_option_id=:product_option_id', array(':product_option_id' => $productoption->id));
             $_productoption[] = array($productoption, $value);
         }
     }
     return $_productoption;
 }
Ejemplo n.º 4
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = ProductOption::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id]);
     $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'presentation', $this->presentation]);
     return $dataProvider;
 }
Ejemplo n.º 5
0
 public function setUp()
 {
     parent::setUp();
     $this->product = Product::getNewInstance(Category::getRootNode(), 'test');
     $this->product->save();
     $this->option = ProductOption::getNewInstance($this->product);
     $this->option->type->set(ProductOption::TYPE_SELECT);
     $this->option->save();
     for ($k = 0; $k <= 1; $k++) {
         $choice = ProductOptionChoice::getNewInstance($this->option);
         $choice->priceDiff->set(10 + $k);
         $choice->save();
         $this->choices[] = $choice;
     }
 }
Ejemplo n.º 6
0
    /**
     * Returns category products
     *
     * @param int         $id_lang                Language ID
     * @param int         $p                      Page number
     * @param int         $n                      Number of products per page
     * @param string|null $order_by               ORDER BY column
     * @param string|null $order_way              Order way
     * @param bool        $get_total              If set to true, returns the total number of results only
     * @param bool        $active                 If set to true, finds only active products
     * @param bool        $random                 If true, sets a random filter for returned products
     * @param int         $random_number_products Number of products to return if random is activated
     * @param bool        $check_access           If set tot rue, check if the current customer
     *                                            can see products from this category
     * @param Context|null $context
     *
     * @return array|int|false Products, number of products or false (no access)
     * @throws PrestaShopDatabaseException
     */
    public function getProducts($id_lang, $p, $n, $order_by = null, $order_way = null, $get_total = false, $active = true, $random = false, $random_number_products = 1, $check_access = true, Context $context = null, $options = null)
    {
        if (!$context) {
            $context = Context::getContext();
        }
        if ($check_access && !$this->checkAccess($context->customer->id)) {
            return false;
        }
        $front = in_array($context->controller->controller_type, array('front', 'modulefront'));
        $id_supplier = (int) Tools::getValue('id_supplier');
        /** Return only the number of products */
        if ($get_total) {
            $sql = 'SELECT COUNT(cp.`id_product`) AS total
					FROM `' . _DB_PREFIX_ . 'product` p
					' . Shop::addSqlAssociation('product', 'p') . '
					LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON p.`id_product` = cp.`id_product`
					WHERE cp.`id_category` = ' . (int) $this->id . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . ($active ? ' AND product_shop.`active` = 1' : '') . ($id_supplier ? 'AND p.id_supplier = ' . (int) $id_supplier : '');
            return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
        }
        if ($p < 1) {
            $p = 1;
        }
        /** Tools::strtolower is a fix for all modules which are now using lowercase values for 'orderBy' parameter */
        $order_by = Validate::isOrderBy($order_by) ? Tools::strtolower($order_by) : 'position';
        $order_way = Validate::isOrderWay($order_way) ? Tools::strtoupper($order_way) : 'ASC';
        $order_by_prefix = false;
        if ($order_by == 'id_product' || $order_by == 'date_add' || $order_by == 'date_upd') {
            $order_by_prefix = 'p';
        } elseif ($order_by == 'name') {
            $order_by_prefix = 'pl';
        } elseif ($order_by == 'manufacturer' || $order_by == 'manufacturer_name') {
            $order_by_prefix = 'm';
            $order_by = 'name';
        } elseif ($order_by == 'position') {
            $order_by_prefix = 'cp';
        }
        if ($order_by == 'price') {
            $order_by = 'orderprice';
        }
        if ($options) {
            $optionsSql = ' AND pop.id_product_option IN (' . implode(",", $options) . ')';
            $optionHaving = ' having count(distinct pop.id_product_option)=' . count($options);
        }
        $nb_days_new_product = Configuration::get('PS_NB_DAYS_NEW_PRODUCT');
        if (!Validate::isUnsignedInt($nb_days_new_product)) {
            $nb_days_new_product = 20;
        }
        $sql = 'SELECT p.*, product_shop.*, stock.out_of_stock, IFNULL(stock.quantity, 0) AS quantity' . (Combination::isFeatureActive() ? ', IFNULL(product_attribute_shop.id_product_attribute, 0) AS id_product_attribute,
					product_attribute_shop.minimal_quantity AS product_attribute_minimal_quantity' : '') . ', pl.`description`, pl.`description_short`, pl.`available_now`,
					pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, image_shop.`id_image` id_image,
					il.`legend` as legend, m.`name` AS manufacturer_name, cl.`name` AS category_default,
					DATEDIFF(product_shop.`date_add`, DATE_SUB("' . date('Y-m-d') . ' 00:00:00",
					INTERVAL ' . (int) $nb_days_new_product . ' DAY)) > 0 AS new, product_shop.price AS orderprice
				FROM `' . _DB_PREFIX_ . 'category_product` cp
				LEFT JOIN `' . _DB_PREFIX_ . 'product` p
					ON p.`id_product` = cp.`id_product`
				' . Shop::addSqlAssociation('product', 'p') . (Combination::isFeatureActive() ? ' LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_shop` product_attribute_shop
				ON (p.`id_product` = product_attribute_shop.`id_product` AND product_attribute_shop.`default_on` = 1 AND product_attribute_shop.id_shop=' . (int) $context->shop->id . ')' : '') . '
				' . Product::sqlStock('p', 0) . '
				LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl
					ON (product_shop.`id_category_default` = cl.`id_category`
					AND cl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('cl') . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl
					ON (p.`id_product` = pl.`id_product`
					AND pl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('pl') . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop
					ON (image_shop.`id_product` = p.`id_product` AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $context->shop->id . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il
					ON (image_shop.`id_image` = il.`id_image`
					AND il.`id_lang` = ' . (int) $id_lang . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m
					ON m.`id_manufacturer` = p.`id_manufacturer`
				LEFT JOIN `' . _DB_PREFIX_ . 'product_option_product` pop
					ON pop.`id_product` = p.`id_product`
				WHERE product_shop.`id_shop` = ' . (int) $context->shop->id . '
					AND cp.`id_category` = ' . (int) $this->id . ($active ? ' AND product_shop.`active` = 1' : '') . ($optionsSql ? $optionsSql : '') . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . ($id_supplier ? ' AND p.id_supplier = ' . (int) $id_supplier : '') . ' GROUP BY cp.id_product' . ($optionHaving ? $optionHaving : '');
        if ($random === true) {
            $sql .= ' ORDER BY RAND() LIMIT ' . (int) $random_number_products;
        } else {
            $sql .= ' ORDER BY ' . (!empty($order_by_prefix) ? $order_by_prefix . '.' : '') . '`' . bqSQL($order_by) . '` ' . pSQL($order_way) . '
			LIMIT ' . ((int) $p - 1) * (int) $n . ',' . (int) $n;
        }
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql, true, false);
        if (!$result) {
            return array();
        }
        if ($order_by == 'orderprice') {
            Tools::orderbyPrice($result, $order_way);
        }
        foreach ($result as $key => $value) {
            if (ProductOption::getProductOptionsProduct($value['id_product'], (int) $id_lang)) {
                $result[$key]['product_options'] = ProductOption::getProductOptionsProduct($value['id_product'], (int) $id_lang);
            }
        }
        /** Modify SQL result */
        return Product::getProductsProperties($id_lang, $result);
    }
Ejemplo n.º 7
0
 /**
  * Initializes page content variables
  */
 public function initContent()
 {
     parent::initContent();
     $this->setTemplate(_PS_THEME_DIR_ . 'category.tpl');
     if (!$this->customer_access) {
         return;
     }
     if (isset($this->context->cookie->id_compare)) {
         $this->context->smarty->assign('compareProducts', CompareProduct::getCompareProducts((int) $this->context->cookie->id_compare));
     }
     // Product sort must be called before assignProductList()
     $this->productSort();
     $this->assignScenes();
     $this->assignSubcategories();
     $this->assignProductList();
     $products = $this->category->getProducts($this->context->language->id, (int) $this->p, (int) $this->n, $this->orderBy, $this->orderWay);
     $products_options = ProductOption::getProductOptions($this->context->language->id);
     $combinations = $this->getProductAttributeCombinations($products);
     //        $this->context->smarty->assign('combinations', $combinations);
     $this->context->smarty->assign(array('category' => $this->category, 'combinations' => $combinations, 'description_short' => Tools::truncateString($this->category->description, 350), 'products' => isset($this->cat_products) && $this->cat_products ? $this->cat_products : null, 'products_options' => isset($products_options) && $products_options ? $products_options : null, 'id_category' => (int) $this->category->id, 'id_category_parent' => (int) $this->category->id_parent, 'return_category_name' => Tools::safeOutput($this->category->name), 'path' => Tools::getPath($this->category->id), 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'categorySize' => Image::getSize(ImageType::getFormatedName('category')), 'mediumSize' => Image::getSize(ImageType::getFormatedName('medium')), 'thumbSceneSize' => Image::getSize(ImageType::getFormatedName('m_scene')), 'homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'allow_oosp' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'suppliers' => Supplier::getSuppliers(), 'body_classes' => array($this->php_self . '-' . $this->category->id, $this->php_self . '-' . $this->category->link_rewrite)));
 }
Ejemplo n.º 8
0
 public function getOptions($includeInheritedOptions = false)
 {
     ClassLoader::import('application.model.product.ProductOption');
     $f = new ARSelectFilter();
     if ($includeInheritedOptions) {
         $ids = array();
         foreach (array_reverse($this->getPathNodeArray(true)) as $cat) {
             $ids[] = $cat['ID'];
             $f->setOrder(new ARExpressionHandle('ProductOption.categoryID=' . $cat['ID']), 'DESC');
         }
         $f->setCondition(new INCond(new ARFieldHandle('ProductOption', 'categoryID'), $ids));
     } else {
         $f->setCondition(new EqualsCond(new ARFieldHandle('ProductOption', 'categoryID'), $this->getID()));
     }
     $f->setOrder(new ARFieldHandle('ProductOption', 'position'), 'ASC');
     return ProductOption::getRecordSet($f, array('ProductOptionChoice'));
 }
Ejemplo n.º 9
0
 public static function getSmallestPrice($product, $includeSize = false)
 {
     $sizew = $sizeh = $bleed = 0;
     if (!isset($product->size_lists)) {
         $smallestSize = SizeList::where('product_id', $product->id)->cacheTags(['size_lists', 'products'])->orderBy('size_lists.sizew', 'asc')->orderBy('size_lists.sizeh', 'asc')->remember(30)->first();
         if (is_object($smallestSize)) {
             $sizew = $smallestSize->sizew;
             $sizeh = $smallestSize->sizeh;
         }
     } else {
         $min = [];
         foreach ($product->size_lists as $size_list) {
             if (!isset($min->sizew) || $min->sizew > $size_list->sizew) {
                 $min = $size_list;
             }
         }
     }
     $smallestDepth = ProductOption::select('name')->whereIn('id', function ($query) use($product) {
         $query->select('optionable_id')->from('optionables')->where('product_id', $product->id)->where('optionable_type', 'ProductOption');
     })->whereIn('option_group_id', function ($query) {
         $query->select('id')->from('option_groups')->where('key', 'depth');
     })->orderBy('key', 'asc')->first();
     if (is_object($smallestDepth)) {
         $bleed = (double) str_replace('" Box', '', $smallestDepth->name);
     }
     if ($sizew && $sizeh || $bleed) {
         $product->sizew = $sizew;
         $product->sizeh = $sizeh;
         $product->bleed = $bleed;
         $price = JTProduct::getPrice($product);
         $sellPrice = $price['sell_price'];
     } else {
         $sellPrice = JTProduct::getDefaultPrice($product);
     }
     if ($includeSize) {
         return ['sell_price' => $sellPrice, 'sizew' => $sizew, 'sizeh' => $sizeh];
     }
     return $sellPrice;
 }
Ejemplo n.º 10
0
 public function testClone()
 {
     $image = ActiveRecordModel::getNewInstance('ProductImage');
     $image->product->set($this->product);
     $image->save();
     $this->assertSame($image, $this->product->defaultImage->get());
     $numField = SpecField::getNewInstance($this->productCategory, SpecField::DATATYPE_NUMBERS, SpecField::TYPE_NUMBERS_SIMPLE);
     $numField->save();
     $this->product->setAttributeValue($numField, 100);
     $this->product->save();
     $option = ProductOption::getNewInstance($this->product);
     $option->type->set(ProductOption::TYPE_SELECT);
     $option->setValueByLang('name', 'en', 'test');
     $option->save();
     $related = Product::getNewInstance($this->productCategory, 'related');
     $related->save();
     $relGroup = ProductRelationshipGroup::getNewInstance($this->product, ProductRelationship::TYPE_CROSS);
     $relGroup->save();
     $rel = ProductRelationship::getNewInstance($this->product, $related, $relGroup);
     $rel->save();
     $this->assertEquals(1, $this->product->getRelationships()->size());
     $cloned = clone $this->product;
     $this->assertEquals(100, $cloned->getSpecification()->getAttribute($numField)->value->get());
     $cloned->setAttributeValue($numField, 200);
     $cloned->setPrice($this->usd, 80);
     $cloned->save();
     $this->assertNotEquals($cloned->getID(), $this->product->getID());
     ActiveRecordModel::clearPool();
     $reloaded = Product::getInstanceByID($cloned->getID(), true);
     $reloaded->loadPricing();
     $this->assertEquals(80, $reloaded->getPrice($this->usd));
     $reloaded->loadSpecification();
     $this->assertEquals(200, $reloaded->getSpecification()->getAttribute($numField)->value->get());
     // related products
     $rel = $reloaded->getRelationships();
     $this->assertEquals(1, $rel->size());
     $this->assertSame($reloaded, $rel->get(0)->productRelationshipGroup->get()->product->get());
     // options
     $clonedOpts = ProductOption::getProductOptions($reloaded);
     $this->assertEquals(1, $clonedOpts->size());
     // image
     $this->assertTrue(is_object($reloaded->defaultImage->get()));
     $this->assertNotEquals($reloaded->defaultImage->get()->getID(), $this->product->defaultImage->get()->getID());
 }
Ejemplo n.º 11
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getOptionsRelation()
 {
     return $this->hasMany(ProductOption::className(), ['id' => 'option_id'])->viaTable('{{%product_type_options}}', ['product_type_id' => 'id']);
 }
Ejemplo n.º 12
0
 function __construct($optionId, $showDisabled = false)
 {
     $option = new ProductOption($optionId);
     $allGroups = new ProductGroups($option->productId(), $showDisabled);
     parent::__construct($option->id(), $allGroups->IDs());
 }
Ejemplo n.º 13
0
 public function validateProductOption($option)
 {
     $valid = true;
     $option->order_id = 0;
     $popt = ProductOption::model()->findByPk($option->product_option_id);
     if ($option->type == 'select' || $option->type == 'radio' || $option->type == 'checkbox') {
         if ($popt->required && (empty($option->product_option_value_id) || !is_numeric($option->product_option_value_id))) {
             $valid = false;
         }
     } else {
         $option->product_option_value_id = 0;
         if ($popt->required && empty($option->value)) {
             $valid = false;
         }
     }
     $valid = $valid && $option->validate();
     Yii::log("OrderOptionCreateActionvaliid: " . $option->name . ' - ' . $valid . '---' . CVarDumper::dumpAsString($option->getErrors()), CLogger::LEVEL_ERROR, "order.actions.create");
     return $valid;
 }
Ejemplo n.º 14
0
 public function setOption(OptionForm $OptionForm)
 {
     if (!empty($this->id)) {
         $id = $this->id;
         Yii::app()->db->createCommand("DELETE FROM {{store_product_option}} WHERE product_id=:id")->bindParam(':id', $id)->execute();
     }
     for ($i = 1; $i <= OptionForm::count; ++$i) {
         if ($OptionForm->{"value_{$i}"} == '') {
             break;
         }
         $option = new ProductOption();
         $option->product_id = $this->id;
         $option->title = $OptionForm->{"title_{$i}"};
         $option->value = $OptionForm->{"value_{$i}"};
         $option->save();
     }
 }
Ejemplo n.º 15
0
 /**
  * Sort options
  *
  * @return JSONResponse
  */
 public function sort()
 {
     $target = $this->request->get('target');
     foreach ($this->request->get($target, array()) as $position => $key) {
         if (!empty($key)) {
             $productOption = ProductOption::getInstanceByID((int) $key);
             $productOption->setFieldValue('position', (int) $position);
             $productOption->save();
         }
     }
     return new JSONResponse(false, 'success');
 }
Ejemplo n.º 16
0
 public function afterDelete()
 {
     // delete dependencies
     ProductAttribute::model()->deleteAll("product_id={$this->cacheId}");
     ProductDescription::model()->deleteAll("product_id={$this->cacheId}");
     ProductDiscount::model()->deleteAll("product_id={$this->cacheId}");
     ProductFilter::model()->deleteAll("product_id={$this->cacheId}");
     ProductImage::model()->deleteAll("product_id={$this->cacheId}");
     ProductOption::model()->deleteAll("product_id={$this->cacheId}");
     ProductOptionValue::model()->deleteAll("product_id={$this->cacheId}");
     ProductRelated::model()->deleteAll("product_id={$this->cacheId}");
     ProductRelated::model()->deleteAll("related_id={$this->cacheId}");
     ProductReward::model()->deleteAll("product_id={$this->cacheId}");
     ProductSpecial::model()->deleteAll("product_id={$this->cacheId}");
     ProductToCategory::model()->deleteAll("product_id={$this->cacheId}");
     ProductToDownload::model()->deleteAll("product_id={$this->cacheId}");
     ProductToLayout::model()->deleteAll("product_id={$this->cacheId}");
     ProductToStore::model()->deleteAll("product_id={$this->cacheId}");
     Review::model()->deleteAll("product_id={$this->cacheId}");
     UrlAlias::model()->deleteAll("query='product_id={$this->cacheId}'");
     parent::afterDelete();
 }
Ejemplo n.º 17
0
 public function __clone()
 {
     parent::__clone();
     $original = $this->originalRecord;
     $original->loadSpecification();
     $this->specificationInstance = clone $original->getSpecification();
     $this->specificationInstance->setOwner($this);
     $original->loadPricing();
     $this->pricingHandlerInstance = clone $original->pricingHandlerInstance;
     $this->pricingHandlerInstance->setProduct($this);
     $this->save();
     // images
     if ($original->defaultImage->get()) {
         foreach ($original->getRelatedRecordSet('ProductImage', $original->getImageFilter()) as $image) {
             $image->_clone($this);
         }
     }
     // options
     foreach (ProductOption::getProductOptions($original) as $option) {
         $clonedOpt = clone $option;
         $clonedOpt->product->set($this);
         $clonedOpt->save();
     }
     // variations
     $variations = $original->getRelatedRecordSet('Product');
     if ($variations->size()) {
         $idMap = array();
         foreach ($original->getRelatedRecordSet('ProductVariationType') as $type) {
             $newType = clone $type;
             $newType->product->set($this);
             $newType->save();
             foreach ($type->getRelatedRecordSet('ProductVariation') as $var) {
                 $newVar = clone $var;
                 $newVar->type->set($newType);
                 $newVar->save();
                 $idMap[$var->getID()] = $newVar->getID();
             }
         }
         foreach ($variations as $variation) {
             $newVariation = clone $variation;
             $newVariation->parent->set($this);
             $newVariation->save();
             foreach ($variation->getRelatedRecordSet('ProductVariationValue') as $value) {
                 $newValue = clone $value;
                 $newValue->product->set($newVariation);
                 $newValue->variation->set(ActiveRecordModel::getInstanceByID('ProductVariation', $idMap[$value->variation->get()->getID()], true));
                 $newValue->save();
             }
         }
     }
     // additional categories
     foreach ($original->getRelatedRecordSet('ProductCategory') as $additionalCat) {
         $newCat = clone $additionalCat;
         $newCat->product->set($this);
         $newCat->save();
     }
     // related products
     $groups[] = array();
     foreach ($original->getRelationships() as $relationship) {
         $group = $relationship->productRelationshipGroup->get();
         $id = $group ? $group->getID() : null;
         if ($id) {
             $groups[$id] = clone $group;
             $groups[$id]->product->set($this);
             $groups[$id]->save();
         }
         $cloned = ProductRelationship::getNewInstance($this, $relationship->relatedProduct->get(), $id ? $groups[$id] : null);
         $cloned->save();
     }
 }
Ejemplo n.º 18
0
 public function testMergeItemsWithOptions()
 {
     $product = $this->products[0];
     $option = ProductOption::getNewInstance($product);
     $option->save();
     $choice1 = ProductOptionChoice::getNewInstance($option);
     $choice1->save();
     $choice2 = ProductOptionChoice::getNewInstance($option);
     $choice2->save();
     $order = CustomerOrder::getNewInstance($this->user);
     $item = $order->addProduct($product, 1);
     $this->assertIsA($item, 'OrderedItem');
     $this->assertEqual(count($order->getShoppingCartItemCount()), 1);
     $order->addProduct($product, 1);
     $this->assertEqual(count($order->getItemsByProduct($product)), 2);
     $this->assertEqual($order->getShoppingCartItemCount(), 2);
     // merge without options
     $order->mergeItems();
     $this->assertEqual(count($order->getItemsByProduct($product)), 1);
     $this->assertEqual($order->getShoppingCartItemCount(), 2);
     // merge with options
     $item = array_shift($order->getItemsByProduct($product));
     $item->count->set(1);
     $item->addOptionChoice($choice1);
     $item2 = $order->addProduct($product, 1);
     $item2->addOptionChoice($choice2);
     $order->mergeItems();
     $this->assertEqual(count($order->getItemsByProduct($product)), 2);
     $this->assertEqual($order->getShoppingCartItemCount(), 2);
     // set same options
     $item2->removeOptionChoice($choice2);
     $item2->addOptionChoice($choice1);
     $order->mergeItems();
     $this->assertEqual(count($order->getItemsByProduct($product)), 1);
     $this->assertEqual($order->getShoppingCartItemCount(), 2);
 }
Ejemplo n.º 19
0
<?php

$this->breadcrumbs = array('Product Attributes' => array('index'), 'Manage');
$this->menu = array(array('label' => 'List ProductAttribute', 'url' => array('index')), array('label' => 'Create ProductAttribute', 'url' => array('create')));
?>

<h1>Manage Product Attributes</h1>
<div>
<?php 
echo CHtml::link('Add Product Attribute', array('ProductAttribute/create'));
?>
 |
<?php 
echo CHtml::link('Manage Product Option', array('ProductOption/admin'));
?>
 |
<?php 
echo CHtml::link('Manage Option Value', array('ProductOptionValue/admin'));
?>
</div>

<?php 
$this->widget('zii.widgets.grid.CGridView', array('id' => 'product-attribute-grid', 'dataProvider' => $model->search(), 'filter' => $model, 'summaryText' => '', 'pager' => array('header' => '', 'firstPageLabel' => '| <', 'lastPageLabel' => '> |', 'nextPageLabel' => '>', 'prevPageLabel' => '<'), 'columns' => array('product_attribute_id', array('name' => 'product_id', 'type' => 'html', 'value' => '$data->product->product_name', 'sortable' => TRUE, 'filter' => CHtml::listData(Product::model()->findAll(), 'product_id', 'product_name')), array('name' => 'product_option_id', 'type' => 'html', 'value' => '$data->productOption->product_option_name', 'sortable' => TRUE, 'filter' => CHtml::listData(ProductOption::model()->findAll(), 'product_option_id', 'product_option_name')), array('name' => 'option_value_id', 'type' => 'html', 'value' => '$data->productOptionValue->product_option_value_name', 'sortable' => TRUE, 'filter' => CHtml::listData(ProductOptionValue::model()->findAll(), 'product_option_value_id', 'product_option_value_name')), 'option_value_price', array('class' => 'CButtonColumn', 'template' => '{update}&nbsp;&nbsp;{delete}'))));
Ejemplo n.º 20
0
 private function getItemResponse(OrderedItem $item)
 {
     $item->customerOrder->get()->load();
     $item->customerOrder->get()->loadItems();
     if ($image = $item->getProduct()->defaultImage->get()) {
         $image->load();
     }
     $this->application->getLocale()->translationManager()->loadFile('backend/Shipment');
     $response = new ActionResponse('item', $item->toArray());
     // load product options and variations
     $response->set('allOptions', ProductOption::loadOptionsForProductSet($item->getProduct()->getParent()->initSet()));
     $response->set('variations', $item->getProduct()->getParent()->initSet()->getVariationData($this->application));
     return $response;
 }
Ejemplo n.º 21
0
 private function shipmentInfo($response)
 {
     $order = CustomerOrder::getInstanceById($this->request->get('id'), true, true);
     $order->loadAll();
     $order->getCoupons();
     $products = ARSet::buildFromArray($order->getOrderedItems())->extractReferencedItemSet('product', 'ProductSet');
     $variations = $products->getVariationMatrix();
     $form = $this->createShipmentForm();
     $form->setData(array('orderID' => $order->getID()));
     $shipments = $order->getShipments();
     $zone = $order->getDeliveryZone();
     $taxZone = $order->getTaxZone();
     $statuses = array(Shipment::STATUS_NEW => $this->translate('_shipping_status_new'), Shipment::STATUS_PROCESSING => $this->translate('_shipping_status_pending'), Shipment::STATUS_AWAITING => $this->translate('_shipping_status_awaiting'), Shipment::STATUS_SHIPPED => $this->translate('_shipping_status_shipped'), Shipment::STATUS_RETURNED => $this->translate('_shipping_status_returned'));
     $subtotalAmount = 0;
     $shippingAmount = 0;
     $taxAmount = 0;
     $itemIDs = $shipmentsArray = array();
     $shipableShipmentsCount = 0;
     foreach ($shipments as $shipment) {
         $subtotalAmount += $shipment->amount->get();
         $shippingAmount += $shipment->shippingAmount->get();
         $taxAmount += $shipment->taxAmount->get();
         $shipmentsArray[$shipment->getID()] = $shipment->toArray();
         $rate = unserialize($shipment->shippingServiceData->get());
         if (is_object($rate)) {
             $rate->setApplication($this->application);
             $shipmentsArray[$shipment->getID()] = array_merge($shipmentsArray[$shipment->getID()], $rate->toArray());
             if (isset($shipmentsArray[$shipment->getID()]['serviceID'])) {
                 $shipmentsArray[$shipment->getID()]['ShippingService']['ID'] = $shipmentsArray[$shipment->getID()]['serviceID'];
             }
         } else {
             if ($shipment->shippingService->get()) {
                 $shipmentsArray[$shipment->getID()]['ShippingService']['name_lang'] = $shipmentsArray[$shipment->getID()]['ShippingService']['name'];
             } else {
                 $shipmentsArray[$shipment->getID()]['ShippingService']['name_lang'] = $this->translate('_shipping_service_is_not_selected');
             }
         }
         if ($shipment->status->get() != Shipment::STATUS_SHIPPED && $shipment->isShippable()) {
             $shipableShipmentsCount++;
         }
         foreach ($shipment->getItems() as $item) {
             $itemIDs[] = $item->getID();
         }
     }
     $totalAmount = $subtotalAmount + $shippingAmount + $taxAmount;
     // $response = new ActionResponse();
     $response->set('orderID', $this->request->get('id'));
     $response->set('order', $order->toArray());
     $response->set('shippingServiceIsNotSelected', $this->translate('_shipping_service_is_not_selected'));
     $response->set('shipments', $shipmentsArray);
     $response->set('subtotalAmount', $subtotalAmount);
     $response->set('shippingAmount', $shippingAmount);
     $response->set('variations', $variations);
     if ($downloadable = $order->getDownloadShipment(false)) {
         $response->set('downloadableShipment', $downloadable->toArray());
     }
     $response->set('taxAmount', $taxAmount);
     $response->set('totalAmount', $totalAmount);
     $response->set('shipableShipmentsCount', $shipableShipmentsCount);
     $response->set('statuses', $statuses + array(-1 => $this->translate('_delete')));
     unset($statuses[3]);
     $response->set('statusesWithoutShipped', $statuses);
     $response->set('newShipmentForm', $form);
     $response->set('downloadCount', $this->getDownloadCounts($itemIDs));
     // load product options
     $response->set('allOptions', ProductOption::loadOptionsForProductSet($products));
     return $response;
 }
Ejemplo n.º 22
0
 public function getOptionChoice(ProductOption $option)
 {
     foreach ($this->optionChoices as $choice) {
         if ($choice->choice->get()->option->get()->getID() == $option->getID()) {
             return $choice;
         }
     }
 }
Ejemplo n.º 23
0
 public function importInstance($record, CsvImportProfile $profile)
 {
     $this->className = 'Product';
     $impReq = new Request();
     $defLang = $this->application->getDefaultLanguageCode();
     $references = array('DefaultImage' => 'ProductImage', 'Manufacturer', 'ShippingClass', 'TaxClass');
     $cat = $this->getCategory($profile, $record);
     $extraCategories = null;
     $fields = $profile->getSortedFields();
     if (isset($fields['Categories']['ExtraCategories'])) {
         $extraCategories = explode('; ', $record[$fields['Categories']['ExtraCategories']]);
     }
     if (isset($fields['Product']) && $cat) {
         $product = null;
         if (isset($fields['Product']['ID']) && !empty($record[$fields['Product']['ID']])) {
             $id = $record[$fields['Product']['ID']];
             if (ActiveRecord::objectExists('Product', $id)) {
                 $product = Product::getInstanceByID($id, Product::LOAD_DATA, $references);
             }
         } else {
             if (isset($fields['Product']['sku']) && !empty($record[$fields['Product']['sku']])) {
                 $product = Product::getInstanceBySku($record[$fields['Product']['sku']], $references);
             }
         }
         if ($product && $product->getID()) {
             $this->registerImportedID($product->getID());
         }
         if (!$product && 'update' == $this->options['action'] || $product && 'add' == $this->options['action']) {
             return false;
         }
         if ($product) {
             $product->loadSpecification();
             $product->loadPricing();
         } else {
             if ($cat instanceof Category) {
                 $product = Product::getNewInstance($cat);
             } else {
                 $product = $cat->createChildProduct();
             }
             $product->isEnabled->set(true);
         }
         // product information
         $impReq->clearData();
         foreach ($profile->getFields() as $csvIndex => $field) {
             $column = $field['name'];
             $params = $field['params'];
             if (!isset($record[$csvIndex]) || empty($column)) {
                 continue;
             }
             $value = $record[$csvIndex];
             list($className, $field) = explode('.', $column, 2);
             if (isset($params['language'])) {
                 $lang = $params['language'];
                 if ($lang != $defLang) {
                     $field .= '_' . $lang;
                 }
             }
             if ($value) {
                 if ('Product.parentID' == $column) {
                     $product->parent->set();
                     continue;
                 }
                 if ('Product.parentSKU' == $column) {
                     $product->parent->set(Product::getInstanceBySKU($value));
                     continue;
                 }
             }
             if ('Product.taxClass' == $column) {
                 $product->taxClass->set(TaxClass::findByName($value));
             }
             if ('Product.shippingClass' == $column) {
                 $product->shippingClass->set(ShippingClass::findByName($value));
             }
             if ('Product' == $className) {
                 if ('shippingWeight' == $field) {
                     if ($this->application->getConfig()->get('UNIT_SYSTEM') == 'ENGLISH') {
                         $value = $value / 0.45359237;
                     }
                 }
                 if ('shippingWeight' == $field && $product->parent->get()) {
                     $value = $this->setChildSetting($product, 'weight', $value);
                 }
                 $impReq->set($field, $value);
             } else {
                 if ('Manufacturer' == $className) {
                     $impReq->set('manufacturer', $value);
                 } else {
                     if ('ProductPrice.price' == $column) {
                         if ($product->parent->get()) {
                             $value = $this->setChildSetting($product, 'price', $value);
                         }
                         $value = preg_replace('/,([0-9]{3})/', '\\1', $value);
                         $value = (double) preg_replace('/[^\\.0-9]/', '', str_replace(',', '.', $value));
                         $currency = isset($params['currency']) ? $params['currency'] : $this->application->getDefaultCurrencyCode();
                         $quantityLevel = isset($params['quantityLevel']) ? $params['quantityLevel'] : '';
                         $group = isset($params['group']) ? $params['group'] : '';
                         $price = $product->getPricingHandler()->getPriceByCurrencyCode($currency);
                         $product->getPricingHandler()->setPrice($price);
                         if ($group || $quantityLevel) {
                             if ($value > 0) {
                                 $quantity = $quantityLevel ? $record[$fields['ProductPrice'][$quantityLevel]] : 1;
                                 $group = $group ? UserGroup::getInstanceByID($group) : null;
                                 $price->setPriceRule($quantity, $group, $value);
                             }
                         } else {
                             $price->price->set($value);
                         }
                     } else {
                         if ('ProductPrice.listPrice' == $column) {
                             $value = (double) preg_replace('/[^\\.0-9]/', '', str_replace(',', '.', $value));
                             $currency = $params['currency'];
                             $price = $product->getPricingHandler()->getPriceByCurrencyCode($currency);
                             $price->listPrice->set($value);
                             $product->getPricingHandler()->setPrice($price);
                         } else {
                             if ('ProductVariation' == $className) {
                                 if ($parent = $product->parent->get()) {
                                     $this->importProductVariationValue($product, $field, $value);
                                 } else {
                                     $this->importVariationType($product, $field, $value);
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $product->loadRequestData($impReq);
         $product->save();
         $this->importAttributes($product, $record, $fields, 'specField');
         $this->setLastImportedRecordName($product->getValueByLang('name'));
         if (isset($fields['ProductImage']['mainurl'])) {
             if (!($image = $product->defaultImage->get())) {
                 $image = ProductImage::getNewInstance($product);
             }
             $image->setOwner($product);
             // this is needed when ProductApi imports default ProductImage.
             $this->importImage($image, $record[$fields['ProductImage']['mainurl']]);
             unset($image);
         }
         if (isset($fields['ProductAdditionalImage'])) {
             foreach ($fields['ProductAdditionalImage'] as $index) {
                 $this->importImage(ProductImage::getNewInstance($product), $record[$index]);
             }
         }
         if (isset($fields['ProductImage']['Images'])) {
             $images = explode('; ', $record[$fields['ProductImage']['Images']]);
             if ($images) {
                 $product->deleteRelatedRecordSet('ProductImage');
                 foreach ($images as $path) {
                     $image = ProductImage::getNewInstance($product);
                     $this->importImage($image, $path);
                     unset($image);
                 }
             }
         }
         if (isset($fields['ProductOption']['options'])) {
             $options = explode('; ', $record[$fields['ProductOption']['options']]);
             if ($options) {
                 $product->deleteRelatedRecordSet('ProductOption');
                 foreach ($options as $option) {
                     $parts = explode(':', $option, 2);
                     if (count($parts) < 2) {
                         continue;
                     }
                     $optionInstance = ProductOption::getNewInstance($product);
                     $optionInstance->setValueByLang('name', null, trim($parts[0]));
                     $optionInstance->type->set(ProductOption::TYPE_SELECT);
                     $optionInstance->isDisplayed->set(true);
                     $optionInstance->save();
                     foreach (explode(',', $parts[1]) as $choice) {
                         $choiceInstance = ProductOptionChoice::getNewInstance($optionInstance);
                         $choiceInstance->setValueByLang('name', null, trim($choice));
                         $choiceInstance->save();
                     }
                 }
             }
         }
         // create variation by name
         if ((isset($fields['Product']['parentID']) || isset($fields['Parent']['parentSKU'])) && !isset($fields['ProductVariation']) && $product->parent->get()) {
             $this->importProductVariationValue($product, 1, $product->getValueByLang('name', 'en'));
         }
         // additional categories
         if (is_array($extraCategories)) {
             $this->importAdditionalCategories($profile, $product, $extraCategories);
         }
         if ($this->callback) {
             call_user_func($this->callback, $product);
         }
         $product->__destruct();
         $product->destruct(true);
         ActiveRecord::clearPool();
         return true;
     }
 }
Ejemplo n.º 24
0
 public static function loadOptionsForProductSet(ARSet $products)
 {
     // load category options
     $f = new ARSelectFilter();
     $categories = $productIDs = array();
     foreach ($products as $product) {
         foreach ($product->getAllCategories() as $cat) {
             $categories[$cat->getID()] = $cat;
         }
         $productIDs[] = $product->getID();
         if ($product->parent->get()) {
             $productIDs[] = $product->parent->get()->getID();
         }
     }
     foreach ($categories as $category) {
         if ($category->isLoaded() == false) {
             $category->load();
         }
         $c = new EqualsOrLessCond(new ARFieldHandle('Category', 'lft'), $category->lft->get());
         $c->addAND(new EqualsOrMoreCond(new ARFieldHandle('Category', 'rgt'), $category->rgt->get()));
         if (!isset($categoryCond)) {
             $categoryCond = $c;
         } else {
             $categoryCond->addOR($c);
         }
     }
     // product options
     $productCond = new INCond(new ARFieldHandle('ProductOption', 'productID'), $productIDs);
     if (!isset($categoryCond)) {
         $categoryCond = $productCond;
     } else {
         $categoryCond->addOR($productCond);
     }
     $f->setCondition($categoryCond);
     // ordering
     $f->setOrder(new ARFieldHandle('ProductOption', 'productID'), 'DESC');
     $f->setOrder(new ARFieldHandle('Category', 'lft'), 'DESC');
     $f->setOrder(new ARFieldHandle('ProductOption', 'position'), 'DESC');
     $options = ProductOption::getRecordSet($f, array('DefaultChoice' => 'ProductOptionChoice', 'Category'));
     self::loadChoicesForRecordSet($options);
     // sort by products
     $sorted = array();
     foreach ($products as $product) {
         foreach ($options as $index => $option) {
             if ($option->product->get() && ($option->product->get()->getID() == $product->getID() || $product->parent->get() && $option->product->get()->getID() == $product->parent->get()->getID())) {
                 $sorted[$product->getID()][] = $option;
             }
             if ($option->category->get()) {
                 $option->category->get()->load();
                 foreach ($product->getAllCategories() as $category) {
                     if ($option->category->get()->isAncestorOf($category)) {
                         $sorted[$product->getID()][] = $option;
                         break;
                     }
                 }
             }
         }
     }
     return $sorted;
 }
Ejemplo n.º 25
0
 public function run()
 {
     $shop = Shop::all()->first();
     if (!$shop) {
         return;
     }
     $shopId = $shop->id;
     $seedData = [['shopify_id' => '32932092380', 'title' => 'Test Product 1', 'handle' => 'test-product-1', 'body_html' => '<h1>Test Product</h1>', 'vendor' => 'Shopify', 'product_type' => 'Shirts', 'published_at' => '', 'published_scope' => 'global', 'template_suffix' => '', 'tags' => ['TEST', 'RED', 'FLEECE', 'SALE', 'NEW'], 'options' => [['shopify_id' => '3490394803498', 'name' => 'Size', 'position' => 1, 'values' => ['XS', 'S', 'M', 'L', 'XL']], ['shopify_id' => '34903903498', 'name' => 'Color', 'position' => 2, 'values' => ['Red', 'Green', 'Blue', 'Purple', 'Black']], ['shopify_id' => '34903948038', 'name' => 'Material', 'position' => 3, 'values' => ['Fleece', 'Cotton', 'Leather', 'Silk']]], 'metafields' => [['shopify_id' => '349009222', 'namespace' => 'global', 'key' => 'size_chart', 'value' => 'https://google.com'], ['shopify_id' => '349009234322', 'namespace' => 'global', 'key' => 'youtube_video_url', 'value' => 'https://google.com'], ['shopify_id' => '3434349009222', 'namespace' => 'global', 'key' => 'sale_channel_url', 'value' => 'https://google.com']], 'variants' => [['shopify_id' => '398798731937', 'title' => 'M Black Fleece', 'price' => '200.99', 'compare_at_price' => '599.99', 'sku' => 'SL-34566', 'barcode' => '39083094-309309083-393094831', 'position' => 1, 'grams' => '', 'inventory_policy' => '', 'inventory_management' => 'shopify', 'inventory_quantity' => 200, 'old_inventory_quantity' => 198, 'fulfillment_service' => '', 'requires_shipping' => true, 'taxable' => true, 'option1' => 'M', 'option2' => 'Black', 'option3' => 'Fleece', 'shopify_image_id' => '', 'weight' => '', 'weight_unit' => 'lbs'], ['shopify_id' => '3987981937', 'title' => 'L Red Leather', 'price' => '2000.99', 'compare_at_price' => '5099.99', 'sku' => 'SL-34566', 'barcode' => '39083094-309309083-393094831', 'position' => 1, 'grams' => '', 'inventory_policy' => '', 'inventory_management' => 'shopify', 'inventory_quantity' => 2000, 'old_inventory_quantity' => 1980, 'fulfillment_service' => '', 'requires_shipping' => true, 'taxable' => true, 'option1' => 'L', 'option2' => 'Red', 'option3' => 'Leather', 'shopify_image_id' => '', 'weight' => '', 'weight_unit' => 'lbs'], ['shopify_id' => '398731937', 'title' => 'XL Purple Silk', 'price' => '400.99', 'compare_at_price' => '699.99', 'sku' => 'SL-34566', 'barcode' => '39083094-309309083-393094831', 'position' => 1, 'grams' => '', 'inventory_policy' => '', 'inventory_management' => 'shopify', 'inventory_quantity' => 200, 'old_inventory_quantity' => 198, 'fulfillment_service' => '', 'requires_shipping' => true, 'taxable' => true, 'option1' => 'XL', 'option2' => 'Purple', 'option3' => 'Silk', 'shopify_image_id' => '', 'weight' => '', 'weight_unit' => 'lbs']]], ['shopify_id' => '329320090980', 'title' => 'Test Product 2', 'handle' => 'test-product-2', 'body_html' => '<h1>Test Product 2</h1>', 'vendor' => 'Shopify', 'product_type' => 'Shirts', 'published_at' => '', 'published_scope' => 'global', 'template_suffix' => '', 'tags' => ['TEST', 'RED', 'FLEECE', 'SALE', 'NEW'], 'options' => [['shopify_id' => '3490394803498', 'name' => 'Size', 'position' => 1, 'values' => ['XS', 'S', 'M', 'L', 'XL']], ['shopify_id' => '34903903498', 'name' => 'Color', 'position' => 2, 'values' => ['Red', 'Green', 'Blue', 'Purple', 'Black']], ['shopify_id' => '34903948038', 'name' => 'Material', 'position' => 3, 'values' => ['Fleece', 'Cotton', 'Leather', 'Silk']]], 'metafields' => [['shopify_id' => '349009222', 'namespace' => 'global', 'key' => 'size_chart', 'value' => 'https://google.com'], ['shopify_id' => '349009234322', 'namespace' => 'global', 'key' => 'youtube_video_url', 'value' => 'https://google.com'], ['shopify_id' => '3434349009222', 'namespace' => 'global', 'key' => 'sale_channel_url', 'value' => 'https://google.com']], 'variants' => [['shopify_id' => '398798731937', 'title' => 'M Black Fleece', 'price' => '200.99', 'compare_at_price' => '599.99', 'sku' => 'SL-34566', 'barcode' => '39083094-309309083-393094831', 'position' => 1, 'grams' => '', 'inventory_policy' => '', 'inventory_management' => 'shopify', 'inventory_quantity' => 200, 'old_inventory_quantity' => 198, 'fulfillment_service' => '', 'requires_shipping' => true, 'taxable' => true, 'option1' => 'M', 'option2' => 'Black', 'option3' => 'Fleece', 'shopify_image_id' => '', 'weight' => '', 'weight_unit' => 'lbs'], ['shopify_id' => '3987981937', 'title' => 'L Red Leather', 'price' => '2000.99', 'compare_at_price' => '5099.99', 'sku' => 'SL-34566', 'barcode' => '39083094-309309083-393094831', 'position' => 1, 'grams' => '', 'inventory_policy' => '', 'inventory_management' => 'shopify', 'inventory_quantity' => 2000, 'old_inventory_quantity' => 1980, 'fulfillment_service' => '', 'requires_shipping' => true, 'taxable' => true, 'option1' => 'L', 'option2' => 'Red', 'option3' => 'Leather', 'shopify_image_id' => '', 'weight' => '', 'weight_unit' => 'lbs'], ['shopify_id' => '398731937', 'title' => 'XL Purple Silk', 'price' => '400.99', 'compare_at_price' => '699.99', 'sku' => 'SL-34566', 'barcode' => '39083094-309309083-393094831', 'position' => 1, 'grams' => '', 'inventory_policy' => '', 'inventory_management' => 'shopify', 'inventory_quantity' => 200, 'old_inventory_quantity' => 198, 'fulfillment_service' => '', 'requires_shipping' => true, 'taxable' => true, 'option1' => 'XL', 'option2' => 'Purple', 'option3' => 'Silk', 'shopify_image_id' => '', 'weight' => '', 'weight_unit' => 'lbs']]], ['shopify_id' => '3293297962380', 'title' => 'Test Product 3', 'handle' => 'test-product-3', 'body_html' => '<h1>Test Product 3</h1>', 'vendor' => 'Shopify', 'product_type' => 'Shirts', 'published_at' => '', 'published_scope' => 'global', 'template_suffix' => '', 'tags' => ['TEST', 'RED', 'FLEECE', 'SALE', 'NEW'], 'options' => [['shopify_id' => '3490394803498', 'name' => 'Size', 'position' => 1, 'values' => ['XS', 'S', 'M', 'L', 'XL']], ['shopify_id' => '34903903498', 'name' => 'Color', 'position' => 2, 'values' => ['Red', 'Green', 'Blue', 'Purple', 'Black']], ['shopify_id' => '34903948038', 'name' => 'Material', 'position' => 3, 'values' => ['Fleece', 'Cotton', 'Leather', 'Silk']]], 'metafields' => [['shopify_id' => '349009222', 'namespace' => 'global', 'key' => 'size_chart', 'value' => 'https://google.com'], ['shopify_id' => '349009234322', 'namespace' => 'global', 'key' => 'youtube_video_url', 'value' => 'https://google.com'], ['shopify_id' => '3434349009222', 'namespace' => 'global', 'key' => 'sale_channel_url', 'value' => 'https://google.com']], 'variants' => [['shopify_id' => '398798731937', 'title' => 'M Black Fleece', 'price' => '200.99', 'compare_at_price' => '599.99', 'sku' => 'SL-34566', 'barcode' => '39083094-309309083-393094831', 'position' => 1, 'grams' => '', 'inventory_policy' => '', 'inventory_management' => 'shopify', 'inventory_quantity' => 200, 'old_inventory_quantity' => 198, 'fulfillment_service' => '', 'requires_shipping' => true, 'taxable' => true, 'option1' => 'M', 'option2' => 'Black', 'option3' => 'Fleece', 'shopify_image_id' => '', 'weight' => '', 'weight_unit' => 'lbs'], ['shopify_id' => '3987981937', 'title' => 'L Red Leather', 'price' => '2000.99', 'compare_at_price' => '5099.99', 'sku' => 'SL-34566', 'barcode' => '39083094-309309083-393094831', 'position' => 1, 'grams' => '', 'inventory_policy' => '', 'inventory_management' => 'shopify', 'inventory_quantity' => 2000, 'old_inventory_quantity' => 1980, 'fulfillment_service' => '', 'requires_shipping' => true, 'taxable' => true, 'option1' => 'L', 'option2' => 'Red', 'option3' => 'Leather', 'shopify_image_id' => '', 'weight' => '', 'weight_unit' => 'lbs'], ['shopify_id' => '398731937', 'title' => 'XL Purple Silk', 'price' => '400.99', 'compare_at_price' => '699.99', 'sku' => 'SL-34566', 'barcode' => '39083094-309309083-393094831', 'position' => 1, 'grams' => '', 'inventory_policy' => '', 'inventory_management' => 'shopify', 'inventory_quantity' => 200, 'old_inventory_quantity' => 198, 'fulfillment_service' => '', 'requires_shipping' => true, 'taxable' => true, 'option1' => 'XL', 'option2' => 'Purple', 'option3' => 'Silk', 'shopify_image_id' => '', 'weight' => '', 'weight_unit' => 'lbs']]]];
     DB::table('s_products')->delete();
     foreach ($seedData as $seedProduct) {
         // products
         $product = new Product();
         $product->shop_id = $shopId;
         $product->shopify_id = $seedProduct['shopify_id'];
         $product->title = $seedProduct['title'];
         $product->handle = $seedProduct['handle'];
         $product->body_html = $seedProduct['body_html'];
         $product->vendor = $seedProduct['vendor'];
         $product->product_type = $seedProduct['product_type'];
         $product->published_at = $seedProduct['published_at'];
         $product->published_scope = $seedProduct['published_scope'];
         $product->template_suffix = $seedProduct['template_suffix'];
         $product->tags = implode(',', $seedProduct['tags']);
         $product->save();
         // options
         if (count($seedProduct['options'])) {
             foreach ($seedProduct['options'] as $seedOption) {
                 $option = new ProductOption();
                 $option->product_id = $product->id;
                 $option->shopify_id = $seedOption['shopify_id'];
                 $option->shopify_product_id = $product->shopify_id;
                 $option->name = $seedOption['name'];
                 $option->position = $seedOption['position'];
                 $option->values = implode(',', $seedOption['values']);
                 $option->save();
             }
         }
         // metafields
         if (count($seedProduct['metafields'])) {
             foreach ($seedProduct['metafields'] as $seedMetafield) {
                 $metafield = new ProductMetafield();
                 $metafield->product_id = $product->id;
                 $metafield->shopify_id = $seedMetafield['shopify_id'];
                 $metafield->shopify_product_id = $product->shopify_id;
                 $metafield->namespace = $seedMetafield['namespace'];
                 $metafield->key = $seedMetafield['key'];
                 $metafield->value = $seedMetafield['value'];
                 $metafield->save();
             }
         }
         // variants
         if (count($seedProduct['variants'])) {
             foreach ($seedProduct['variants'] as $seedVariant) {
                 $variant = new ProductVariant();
                 $variant->product_id = $product->id;
                 $variant->shopify_id = $seedVariant['shopify_id'];
                 $variant->shopify_product_id = $product->shopify_id;
                 $variant->title = $seedVariant['title'];
                 $variant->price = $seedVariant['price'];
                 $variant->compare_at_price = $seedVariant['compare_at_price'];
                 $variant->sku = $seedVariant['sku'];
                 $variant->barcode = $seedVariant['barcode'];
                 $variant->position = $seedVariant['position'];
                 $variant->grams = $seedVariant['grams'];
                 $variant->inventory_policy = $seedVariant['inventory_policy'];
                 $variant->inventory_management = $seedVariant['inventory_management'];
                 $variant->inventory_quantity = $seedVariant['inventory_quantity'];
                 $variant->old_inventory_quantity = $seedVariant['old_inventory_quantity'];
                 $variant->fulfillment_service = $seedVariant['fulfillment_service'];
                 $variant->requires_shipping = $seedVariant['requires_shipping'];
                 $variant->taxable = $seedVariant['taxable'];
                 $variant->option1 = $seedVariant['option1'];
                 $variant->option2 = $seedVariant['option2'];
                 $variant->option3 = $seedVariant['option3'];
                 $variant->shopify_image_id = $seedVariant['shopify_image_id'];
                 $variant->weight = $seedVariant['weight'];
                 $variant->weight_unit = $seedVariant['weight_unit'];
                 $variant->save();
             }
         }
     }
 }
Ejemplo n.º 26
0
<?php

$this->breadcrumbs = array('Product Option Value To Product Options' => array('index'), 'Manage');
$this->menu = array(array('label' => 'List ProductOptionValueToProductOption', 'url' => array('index')), array('label' => 'Create ProductOptionValueToProductOption', 'url' => array('create')));
$this->title = 'Manage Product Option Value To Product Options';
?>

<!-- <h1>Manage Product Option Value To Product Options</h1> -->

<?php 
$this->widget('zii.widgets.grid.CGridView', array('id' => 'product-option-value-to-product-option-grid', 'dataProvider' => $model->search(), 'filter' => $model, 'columns' => array('product_option_value_to_product_option_id', array('name' => 'product_option_id', 'type' => 'html', 'value' => '$data->productOption->product_option_name', 'sortable' => TRUE, 'filter' => CHtml::listData(ProductOption::model()->findAll(), 'product_option_id', 'product_option_name')), array('name' => 'product_option_value_id', 'type' => 'html', 'value' => '$data->productOptionValue->product_option_value_name', 'sortable' => TRUE, 'filter' => CHtml::listData(ProductOptionValue::model()->findAll(), 'product_option_value_id', 'product_option_value_name')), array('class' => 'CButtonColumn', 'template' => '{update}&nbsp;&nbsp;{delete}'))));
Ejemplo n.º 27
0
 public function __clone()
 {
     parent::__clone();
     $original = $this->originalRecord;
     $original->loadSpecification();
     $this->specificationInstance = clone $original->getSpecification();
     $this->specificationInstance->setOwner($this);
     $original->loadPricing();
     $this->pricingHandlerInstance = clone $original->pricingHandlerInstance;
     $this->pricingHandlerInstance->setProduct($this);
     $this->save();
     // images
     if ($original->defaultImage->get()) {
         foreach ($original->getRelatedRecordSet('ProductImage', $original->getImageFilter()) as $image) {
             $image->_clone($this);
         }
     }
     // options
     foreach (ProductOption::getProductOptions($original) as $option) {
         $clonedOpt = clone $option;
         $clonedOpt->product->set($this);
         $clonedOpt->save();
     }
     // related products
     $groups[] = array();
     foreach ($original->getRelationships() as $relationship) {
         $group = $relationship->productRelationshipGroup->get();
         $id = $group ? $group->getID() : null;
         if ($id) {
             $groups[$id] = clone $group;
             $groups[$id]->product->set($this);
             $groups[$id]->save();
         }
         $cloned = ProductRelationship::getNewInstance($this, $relationship->relatedProduct->get(), $id ? $groups[$id] : null);
         $cloned->save();
     }
 }
Ejemplo n.º 28
0
echo $form->labelEx($model, 'product_id');
?>
		<?php 
echo $form->dropDownList($model, 'product_id', CHtml::listData(Product::model()->findAll(), 'product_id', 'product_name'), array('empty' => '--please select--'));
?>
		<?php 
echo $form->error($model, 'product_id');
?>
	</div>
        	
        <div class="row">
		<?php 
echo $form->labelEx($model, 'product_option_id');
?>
		<?php 
echo $form->dropDownList($model, 'product_option_id', CHtml::listData(ProductOption::model()->findAll(), 'product_option_id', 'product_option_name'), array('empty' => '--please select--'));
?>
		<?php 
echo $form->error($model, 'product_option_id');
?>
	</div>
        
        <div class="row">
		<?php 
echo $form->labelEx($model, 'option_value_id');
?>
		<?php 
echo $form->dropDownList($model, 'option_value_id', CHtml::listData(ProductOptionValue::model()->findAll(), 'product_option_value_id', 'product_option_value_name'), array('empty' => '--please select--'));
?>
		<?php 
echo $form->error($model, 'option_value_id');
Ejemplo n.º 29
0
 public static function addOptionValidation(RequestValidator $validator, $option, $fieldName)
 {
     $app = ActiveRecordModel::getApplication();
     if (ProductOption::TYPE_FILE == $option['type']) {
         $checks = array(new IsFileUploadedCheck($app->translate('_err_option_upload')), new IsNotEmptyCheck($app->translate('_err_option_upload')));
         $validator->addCheck($fieldName, new OrCheck(array('upload_' . $fieldName, $fieldName), $checks, $validator->getRequest()));
         if ($types = ProductOption::getFileExtensions($option['fileExtensions'])) {
             $validator->addCheck('upload_' . $fieldName, new IsFileTypeValidCheck($app->maketext('_err_option_filetype', implode(', ', $types)), $types));
         }
         $validator->addCheck('upload_' . $fieldName, new MaxFileSizeCheck($app->maketext('_err_option_filesize', $option['maxFileSize']), $option['maxFileSize']));
     } else {
         $validator->addCheck($fieldName, new IsNotEmptyCheck($app->translate('_err_option_' . $option['type'])));
     }
 }
 /**
  * @param Product $product
  * @throws Exception
  * @throws SmartyException
  */
 public function initFormAttributes($product)
 {
     $data = $this->createTemplate($this->tpl_form);
     $options = ProductOption::getProductOptions($this->context->language->id);
     foreach ($options as &$option) {
         if (isset($product->id) && !empty($product->id)) {
             $option['selected'] = Db::getInstance()->getValue("SELECT id_product_option AS `selected` FROM " . _DB_PREFIX_ . "product_option_product\n                                WHERE id_product={$product->id} AND id_product_option={$option['id_product_option']}");
             $option['amount'] = Db::getInstance()->getValue("SELECT amount AS `amount` FROM " . _DB_PREFIX_ . "product_option_product\n                                WHERE id_product={$product->id} AND id_product_option={$option['id_product_option']}");
         } else {
             $option['selected'] = null;
         }
     }
     $data->assign('options', $options);
     if (!Combination::isFeatureActive()) {
         $this->displayWarning($this->l('This feature has been disabled. ') . ' <a href="index.php?tab=AdminPerformance&token=' . Tools::getAdminTokenLite('AdminPerformance') . '#featuresDetachables">' . $this->l('Performances') . '</a>');
     } elseif (Validate::isLoadedObject($product)) {
         if ($this->product_exists_in_shop) {
             if ($product->is_virtual) {
                 $data->assign('product', $product);
                 $this->displayWarning($this->l('A virtual product cannot have combinations.'));
             } else {
                 $attribute_js = array();
                 $attributes = Attribute::getAttributes($this->context->language->id, true);
                 foreach ($attributes as $k => $attribute) {
                     $attribute_js[$attribute['id_attribute_group']][$attribute['id_attribute']] = $attribute['name'];
                     natsort($attribute_js[$attribute['id_attribute_group']]);
                 }
                 $currency = $this->context->currency;
                 $data->assign('attributeJs', $attribute_js);
                 $data->assign('attributes_groups', AttributeGroup::getAttributesGroups($this->context->language->id));
                 $data->assign('currency', $currency);
                 $images = Image::getImages($this->context->language->id, $product->id);
                 $data->assign('tax_exclude_option', Tax::excludeTaxeOption());
                 $data->assign('ps_weight_unit', Configuration::get('PS_WEIGHT_UNIT'));
                 $data->assign('ps_use_ecotax', Configuration::get('PS_USE_ECOTAX'));
                 $data->assign('field_value_unity', $this->getFieldValue($product, 'unity'));
                 $data->assign('reasons', $reasons = StockMvtReason::getStockMvtReasons($this->context->language->id));
                 $data->assign('ps_stock_mvt_reason_default', $ps_stock_mvt_reason_default = Configuration::get('PS_STOCK_MVT_REASON_DEFAULT'));
                 $data->assign('minimal_quantity', $this->getFieldValue($product, 'minimal_quantity') ? $this->getFieldValue($product, 'minimal_quantity') : 1);
                 $data->assign('available_date', $this->getFieldValue($product, 'available_date') != 0 ? stripslashes(htmlentities($this->getFieldValue($product, 'available_date'), $this->context->language->id)) : '0000-00-00');
                 $i = 0;
                 $type = ImageType::getByNameNType('%', 'products', 'height');
                 if (isset($type['name'])) {
                     $data->assign('imageType', $type['name']);
                 } else {
                     $data->assign('imageType', ImageType::getFormatedName('small'));
                 }
                 $data->assign('imageWidth', (isset($image_type['width']) ? (int) $image_type['width'] : 64) + 25);
                 foreach ($images as $k => $image) {
                     $images[$k]['obj'] = new Image($image['id_image']);
                     ++$i;
                 }
                 $data->assign('images', $images);
                 $data->assign($this->tpl_form_vars);
                 $data->assign(array('list' => $this->renderListAttributes($product, $currency), 'product' => $product, 'id_category' => $product->getDefaultCategory(), 'token_generator' => Tools::getAdminTokenLite('AdminAttributeGenerator'), 'combination_exists' => Shop::isFeatureActive() && Shop::getContextShopGroup()->share_stock && count(AttributeGroup::getAttributesGroups($this->context->language->id)) > 0 && $product->hasAttributes()));
             }
         } else {
             $this->displayWarning($this->l('You must save the product in this shop before adding combinations.'));
         }
     } else {
         $data->assign('product', $product);
         $this->displayWarning($this->l('You must save this product before adding combinations.'));
     }
     $this->tpl_form_vars['custom_form'] = $data->fetch();
 }