public function processAfterSave(Mage_Catalog_Model_Product $object, $forceId = null) { $associated = array(); switch ($object->getTypeId()) { case Mage_Catalog_Model_Product_Type::TYPE_GROUPED: $associated = $object->getTypeInstance()->getAssociatedProducts(); break; case Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE: $associated = $object->getTypeInstance()->getUsedProducts(); break; } if (!$this->_isObjectIndexable($object) && is_null($forceId)) { return; } $data = array(); if ($this->_runOnce) { $data = $this->createIndexData($object); } else { $attributes = $object->getAttributes(); foreach ($attributes as $attribute) { if ($this->_isAttributeIndexable($attribute) && $object->getData($attribute->getAttributeCode()) != null) { $row = $this->createIndexData($object, $attribute); if ($row && is_array($row)) { if (isset($row[0]) && is_array($row[0])) { $data = array_merge($data, $row); } else { $data[] = $row; } } } } } $function = 'saveIndex'; if ($data && is_array($data)) { if (isset($data[0]) && is_array($data[0])) { $function = 'saveIndices'; } $this->{$function}($data, $object->getStoreId(), $forceId != null ? $forceId : $object->getId()); } if (!$this->_processChildrenForConfigurable && $object->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { return; } if ($associated && $this->_processChildren) { foreach ($associated as $child) { $child->setStoreId($object->getStoreId())->setWebsiteId($object->getWebsiteId()); $this->processAfterSave($child, $object->getId()); } } }
public function testGetSetTypeInstance() { // model getter $typeInstance = $this->_model->getTypeInstance(); $this->assertInstanceOf('Mage_Bundle_Model_Product_Type', $typeInstance); $this->assertSame($typeInstance, $this->_model->getTypeInstance()); // singleton getter $otherProduct = Mage::getModel('Mage_Catalog_Model_Product'); $otherProduct->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_BUNDLE); $this->assertSame($typeInstance, $otherProduct->getTypeInstance()); // model setter $customTypeInstance = Mage::getModel('Mage_Bundle_Model_Product_Type'); $this->_model->setTypeInstance($customTypeInstance); $this->assertSame($customTypeInstance, $this->_model->getTypeInstance()); }
public function testGetSetTypeInstance() { // model getter $typeInstance = $this->_model->getTypeInstance(); $this->assertInstanceOf('Mage_Catalog_Model_Product_Type_Abstract', $typeInstance); $this->assertSame($typeInstance, $this->_model->getTypeInstance()); // singleton /** @var $otherProduct Mage_Catalog_Model_Product */ $otherProduct = Mage::getModel('Mage_Catalog_Model_Product'); $this->assertSame($typeInstance, $otherProduct->getTypeInstance()); // model setter $simpleTypeInstance = Mage::getModel('Mage_Catalog_Model_Product_Type_Simple'); $this->_model->setTypeInstance($simpleTypeInstance); $this->assertSame($simpleTypeInstance, $this->_model->getTypeInstance()); }
/** * Add different params (options price) to price * @param Mage_Catalog_Model_Product $product * @param int $qty * @param float $price * @return float */ protected function _applySpecialPrice($product, $finalPrice) { if ($product->getAwSarpEnabled() && $product->getTypeInstance()->getDefaultSubscriptionPeriodId() != AW_Sarp_Model_Period::PERIOD_TYPE_NONE) { return $finalPrice; } return parent::_applySpecialPrice($product, $finalPrice); }
/** * Save configurable product relations * * @param Mage_Catalog_Model_Product|int $mainProduct the parent id * @param array $productIds the children id array * @return Mage_Catalog_Model_Resource_Product_Type_Configurable */ public function saveProducts($mainProduct, $productIds) { $isProductInstance = false; if ($mainProduct instanceof Mage_Catalog_Model_Product) { $mainProductId = $mainProduct->getId(); $isProductInstance = true; } else { $mainProductId = $mainProduct; } $old = $mainProduct->getTypeInstance()->getUsedProductIds(); $insert = array_diff($productIds, $old); $delete = array_diff($old, $productIds); if ((!empty($insert) || !empty($delete)) && $isProductInstance) { $mainProduct->setIsRelationsChanged(true); } if (!empty($delete)) { $where = array('parent_id = ?' => $mainProductId, 'product_id IN(?)' => $delete); $this->_getWriteAdapter()->delete($this->getMainTable(), $where); } if (!empty($insert)) { $data = array(); foreach ($insert as $childId) { $data[] = array('product_id' => (int) $childId, 'parent_id' => (int) $mainProductId); } $this->_getWriteAdapter()->insertMultiple($this->getMainTable(), $data); } // configurable product relations should be added to relation table Mage::getResourceSingleton('catalog/product_relation')->processRelations($mainProductId, $productIds); return $this; }
public function getItemAttributes() { $productType = $this->product->getTypeId(); switch ($productType) { case Mage_Catalog_Model_Product_Type::TYPE_SIMPLE: $this->item['attributes'] = $this->getProductCustomOptionsOption($this->product); break; case Mage_Catalog_Model_Product_Type::TYPE_BUNDLE: if ($this->product->getTypeInstance(true)->hasOptions($this->product)) { $this->item['attributes'] = $this->getProductBundleOptions($this->product); } break; case Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE: if ($this->product->isConfigurable()) { $this->item['attributes'] = $this->getProductOptions($this->product); } break; case Mage_Catalog_Model_Product_Type::TYPE_GROUPED: $this->item['attributes'] = $this->getProductGroupedOptions($this->product); break; case Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE: // downloadable/catalog_product_links $this->item['attributes'] = $this->getProductDownloadOptions($this->product); break; case Mage_Catalog_Model_Product_Type::TYPE_VIRTUAL: $this->item['attributes'] = array(); break; default: $this->item['attributes'] = array(); break; } return $this->item['attributes']; }
public function createIndexData(Mage_Catalog_Model_Product $object) { $searchEntityId = $object->getId(); $priceAttributeId = $this->getTierPriceAttribute()->getId(); if ($object->isGrouped()) { $priceAttributeId = $this->getPriceAttribute()->getId(); $associated = $object->getTypeInstance()->getAssociatedProducts(); $searchEntityId = array(); foreach ($associated as $product) { $searchEntityId[] = $product->getId(); } } if (!count($searchEntityId)) { return false; } $result = array(); $data = array(); $data['store_id'] = $object->getStoreId(); $data['entity_id'] = $object->getId(); $search['store_id'] = $object->getStoreId(); $search['entity_id'] = $searchEntityId; $search['attribute_id'] = $priceAttributeId; foreach ($this->_customerGroups as $group) { $search['customer_group_id'] = $group->getId(); $data['customer_group_id'] = $group->getId(); $value = $this->_getResource()->getMinimalValue($search); if (is_null($value)) { continue; } $data['value'] = $value; $result[] = $data; } return $result; }
public function testSaveProductRelationsNoChildren() { $childrenIds = $this->_product->getTypeInstance()->getChildrenIds(1); $this->assertNotEmpty(reset($childrenIds)); $this->_product->setAssociatedProductIds(array()); $this->_model->save($this->_product); $this->_product->load(1); $this->assertEquals(array(array()), $this->_product->getTypeInstance()->getChildrenIds(1)); }
/** * For a product get all the parent and children product ids when they are set * * @param Mage_Catalog_Model_Product $oProduct * @return int[] */ protected function getChildrenAndParentIds(Mage_Catalog_Model_Product $oProduct) { $oProductType = $oProduct->getTypeInstance(); $aLinkedProductIds = $oProductType->getParentIdsByChild($oProduct->getId()); $aChildProductIdsByGroups = $oProductType->getChildrenIds($oProduct->getId()); foreach ($aChildProductIdsByGroups as $aChildProductIds) { $aLinkedProductIds = array_unique(array_merge($aLinkedProductIds, $aChildProductIds)); } return $aLinkedProductIds; }
protected function _initConfigurableAttributesData(Mage_Catalog_Model_Product $mainProduct, $simpleProductIds, $priceChanges = array(), $configurableAttributes = array()) { if (!$mainProduct->isConfigurable() || empty($simpleProductIds)) { return $this; } $mainProduct->setConfigurableProductsData(array_flip($simpleProductIds)); $productType = $mainProduct->getTypeInstance(true); $productType->setProduct($mainProduct); $attributesData = $productType->getConfigurableAttributesAsArray(); if (empty($attributesData)) { // Auto generation if configurable product has no attribute $attributeIds = array(); foreach ($productType->getSetAttributes() as $attribute) { if ($productType->canUseAttribute($attribute)) { $attributeIds[] = $attribute->getAttributeId(); } } $productType->setUsedProductAttributeIds($attributeIds); $attributesData = $productType->getConfigurableAttributesAsArray(); } if (!empty($configurableAttributes)) { foreach ($attributesData as $idx => $val) { if (!in_array($val['attribute_id'], $configurableAttributes)) { unset($attributesData[$idx]); } } } $products = Mage::getModel('catalog/product')->getCollection()->addIdFilter($simpleProductIds); if (count($products)) { foreach ($attributesData as $i => $attribute) { $attribute['label'] = $attribute['frontend_label']; $attributeCode = $attribute['attribute_code']; foreach ($products as $product) { $product->load($product->getId()); $optionId = $product->getData($attributeCode); $isPercent = 0; $priceChange = 0; if (!empty($priceChanges) && isset($priceChanges[$attributeCode])) { $optionText = $product->getResource()->getAttribute($attribute['attribute_code'])->getSource()->getOptionText($optionId); if (isset($priceChanges[$attributeCode][$optionText])) { if (false !== strpos($priceChanges[$attributeCode][$optionText], '%')) { $isPercent = 1; } $priceChange = preg_replace('/[^0-9\\.,-]/', '', $priceChanges[$attributeCode][$optionText]); $priceChange = (double) str_replace(',', '.', $priceChange); } } $attribute['values'][$optionId] = array('value_index' => $optionId, 'is_percent' => $isPercent, 'pricing_value' => $priceChange); } $attributesData[$i] = $attribute; } $mainProduct->setConfigurableAttributesData($attributesData); } return $this; }
/** * Retrieves the option collection of a bundle including their respective selections. * * @param Mage_Catalog_Model_Product $product The product * @param bool $appendAll Whether to get all selections or just those saleable * @return array */ public function getOptions(Mage_Catalog_Model_Product $product, $appendAll = true) { $typeInstance = $product->getTypeInstance(true); $typeInstance->setStoreFilter($product->getStoreId(), $product); $optionCollection = $typeInstance->getOptionsCollection($product); $optionIds = $typeInstance->getOptionsIds($product); $selectionIds = array(); $selectionCollection = $typeInstance->getSelectionsCollection($optionIds, $product); $options = $optionCollection->appendSelections($selectionCollection, false, $appendAll); return $options; }
/** * @param Mage_Catalog_Model_Product $product * @return Mage_Catalog_Model_Product[] */ protected function getPossibleSimpleProducts($product) { /** @var Mage_Catalog_Model_Product_Type_Configurable $productTypeIns */ $productTypeIns = $product->getTypeInstance(true); $children = $productTypeIns->getUsedProductCollection($product); $children->addAttributeToSelect('thumbnail'); foreach (array_keys($this->requestConfigurableMap) as $code) { $children->addAttributeToSelect($code); } return $children; }
private function guardAgainstConfigurableAttributeNotInDestinationAttributeSet(Mage_Catalog_Model_Product $product, $attributeSetId) { $type = $product->getTypeInstance(); if (!$type instanceof Mage_Catalog_Model_Product_Type_Configurable) { return; } foreach ($type->getConfigurableAttributes($product) as $configurableAttribute) { $attribute = Mage::getModel('eav/entity_attribute')->load($configurableAttribute->getAttributeId()); if ($this->isAttributeInAttributeSet($attribute, $attributeSetId)) { throw new RuntimeException($this->__('The configurable attribute "%s" is not available in the targeted attribute set. Please create it first!', $attribute->getFrontendLabel())); } } }
/** * Returns HTML with attribute images * * @param Mage_Catalog_Model_Product $product * @param string $mode (view, list, grid) * @param array $names arrtibute codes to show images for * @param bool $exclude flag to indicate taht we need to show all attributes beside specified in $names * @return unknown */ public function showLinks($product, $mode = 'view', $names = array(), $exclude = false) { if ('view' == $mode) { $this->init(array($product)); } $filters = $this->_getFilters(); $items = array(); foreach ($filters as $filter) { $code = $filter->getAttributeCode(); if (!$code) { continue; } if ($names && in_array($code, $names) && $exclude) { continue; } if ($names && !in_array($code, $names) && !$exclude) { continue; } $optIds = trim($product->getData($code), ','); if (!$optIds) { if (!$product->isGrouped() && $product->getTypeInstance(true)->isComposite()) { foreach ($product->getTypeInstance(true)->getUsedProducts(null, $product) as $child) { if ($child->getData($code)) { $optIds .= $child->getData($code) . ','; } } } } if ($optIds) { $optIds = explode(',', $optIds); $optIds = array_unique($optIds); foreach ($optIds as $id) { if (!empty($this->icons[$id])) { $items[] = $this->icons[$id]; } } } } //sort by position in the layered navigation usort($items, array('Amasty_Shopby_Helper_Data', '_srt')); //create block $block = Mage::getModel('core/layout')->createBlock('core/template')->setArea('frontend')->setTemplate('amshopby/links.phtml'); $block->assign('_type', 'html')->assign('_section', 'body')->setLinks($items)->setMode($mode); // to be able to created different html return $block->toHtml(); }
/** * @param Mage_Catalog_Model_Product $product * @return Mage_Catalog_Model_Product|null */ protected function getMatchingSimpleProduct($product) { /** @var Mage_Catalog_Model_Product_Type_Configurable $productTypeIns */ $productTypeIns = $product->getTypeInstance(true); $children = $productTypeIns->getUsedProductCollection($product); foreach ($this->requestConfigurableMap as $code => $values) { $children->addAttributeToFilter($code, array('in' => $values)); } $ids = $children->getAllIds(); $resultChild = null; foreach ($ids as $id) { $child = Mage::getModel('catalog/product')->load($id); if ($child->getThumbnail() != 'no_selection') { $resultChild = $child; } } return $resultChild; }
/** * Add products used to configure this product. * @param Mage_Catalog_Model_Product $product Configurable parent product to add children to. * @return $this object */ protected function _addUsedProducts(Mage_Catalog_Model_Product $product) { $addProductIds = array(); foreach ($this->_products as $collectionProduct) { // used product must be simple and have a style id that matches the // configurable product's sku if ($collectionProduct->getTypeId() === Mage_Catalog_Model_Product_Type::TYPE_SIMPLE && $this->_helper->normalizeSku($collectionProduct->getStyleId(), $this->_config->catalogId) === $product->getSku()) { $addProductIds[] = $collectionProduct->getId(); } } // merge the found products with any existing links, filtering out any duplicates $existingIds = $product->getTypeInstance()->getUsedProductIds(); $usedProductIds = array_unique(array_merge($existingIds, $addProductIds)); // only update used products when there are new products to add to the list // update used product when there are addProductIds that are not in existingIds. if (array_diff($addProductIds, $existingIds)) { // save the configurable product links Mage::getResourceModel('catalog/product_type_configurable')->saveProducts($product, $usedProductIds); $product->setData(self::USED_PRODUCT_IDS_PROPERTY, $usedProductIds)->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); } elseif (empty($usedProductIds)) { // @todo put in error confirmation feed $logData = ['sku' => $product->getSku()]; $logMessage = 'No products found to use for configurable product with SKU {sku}'; $this->_logger->warning($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); } return $this; }
/** * Adding configurable product * * @param Mage_Catalog_Model_Product $product * @return Mage_Checkout_Model_Cart */ protected function _addConfigurableProduct(Mage_Catalog_Model_Product $product, $qty = 1) { if ($product->getConfiguredAttributes()) { $subProduct = $product->getTypeInstance()->getProductByAttributes($product->getConfiguredAttributes()); } else { $subProduct = false; } if ($subProduct) { $subProduct->setSuperProduct($product); $item = $this->getQuote()->addCatalogProduct($subProduct, $qty); if ($item->getHasError()) { $this->setLastQuoteMessage($item->getQuoteMessage()); Mage::throwException($item->getMessage()); } } else { $this->getCheckoutSession()->setRedirectUrl($product->getProductUrl()); $this->getCheckoutSession()->setUseNotice(true); Mage::throwException(Mage::helper('checkout')->__('Please specify the- product option(s)')); } return $this; }
/** * Check is email available for product * * @param Mage_Catalog_Model_Product $product * @return bool */ public function isEmailAvailable(Mage_Catalog_Model_Product $product) { if ($product->getTypeInstance()->isTypePhysical()) { return false; } return true; }
/** * Retrieve gallery attribute from product * * @param Mage_Catalog_Model_Product $product * @param Mage_Catalog_Model_Resource_Eav_Mysql4_Attribute|boolean */ protected function _getGalleryAttribute($product) { $attributes = $product->getTypeInstance()->getSetAttributes(); if (!isset($attributes[self::ATTRIBUTE_CODE])) { $this->_fault('not_media'); } return $attributes[self::ATTRIBUTE_CODE]; }
/** * @param Mage_Catalog_Model_Product $product * @return array */ protected function _createSkus(Mage_Catalog_Model_Product $product) { $base_skus = array(); if ($product->isConfigurable()) { /** @var $type Mage_Catalog_Model_Product_Type_Configurable */ $type = $product->getTypeInstance(); $attributeCodes = array(); foreach ($type->getConfigurableAttributesAsArray() as $value) { // Mage::log('attributes configurable: ' . print_r($value, true), null, 'debug.log', true); // Mage::log('attribute_code: ' . $value['attribute_code'], null, 'debug.log', true); $attributeCodes[] = array('code' => $value['attribute_code'], 'label' => $value['label'], 'id' => $value['attribute_id']); foreach ($value['values'] as $val) { // Mage::log('store_label: ' . $val['store_label'], null, 'debug.log', true); } } $groups = $type->getChildrenIds($product->getId()); // Mage::log("groups: " . print_r($groups, true), null, 'debug.log', true); foreach ($groups as $group) { foreach ($group as $childId) { /** @var $childProduct Mage_Catalog_Model_Product */ $childProduct = Mage::getModel('catalog/product')->load($childId); $attributes = array(); foreach ($attributeCodes as $array) { // $attributes[$array['code']] = array('value' => $childProduct->getAttributeText($array['code']), // 'name' => $array['label']); $attributes[] = $childProduct->getTypeInstance(true)->getAttributeById($array['id'], $childProduct); } $attributes = $this->_createAttributes($childProduct, $attributes); $base_skus[] = array('sku' => $childProduct->getSku(), 'attributes' => $attributes); } } } else { $base_skus[] = array('sku' => $product->getSku()); } $stack = array($base_skus); // Mage::log(print_r($stack, true), null, 'debug.log', true); $skus = $this->_findAllSkus($stack); // Mage::log(print_r($skus, true), null, 'debug.log', true); // TODO: Need to test this case again // $sku = $product->getSku(); // if(!isset($sku)) { // return array(); // } $data = array(); foreach ($skus as $node) { $sku = $node['sku']; $attributes = $node['attributes']; $data[] = $this->_createSku($sku, $attributes); } return $data; }
/** * given a DOMNodeList and a Mage_Catalog_Model_Product make sure this is * a product of type configurable and then extract the configurable attribute from the node list * then get the configurable attribute array for each configured attributes * @param DOMNOdeList $nodes the node with configurableAttributes data * @param Mage_Catalog_Model_Product $product * @return array | null an array of configurable attribute data if the given product is configurable otherwise null */ public function extractConfigurableAttributesData(DOMNodeList $nodes, Mage_Catalog_Model_Product $product) { // We are ensuring that the given product is a parent configurable product by first checking if the product sku // doesn't match the product style id. If this condition is met then we know we have a child product and we won't // proceed otherwise we know we have a parent product and proceed continue. if ($product->getSku() !== $this->_normalizeStyleId($product->getStyleId())) { return null; } $typeInstance = $product->getTypeInstance(true); // making sure the right type instance is set on the product if (!$typeInstance instanceof Mage_Catalog_Model_Product_Type_Configurable) { $product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE)->setTypeInstance(Mage_Catalog_Model_Product_Type::factory($product, true), true); } $data = null; // purposely setting this to null just in cause all the attribute already exists // we need to know which configurable attribute we already have for this product // so that we don't try to create the same super attribute relationship which will // cause unique key duplication SQL constraint to be thrown $existedData = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product); foreach (explode(',', strtolower(Mage::helper('eb2ccore')->extractNodeVal($nodes))) as $attributeCode) { // if we don't currently have a super attribute relationship then get the // configurable attribute data if (!$this->_isSuperAttributeExists($existedData, $attributeCode) && $this->_isAttributeInSet($attributeCode, $product)) { $data[] = $this->_getConfiguredAttributeData($attributeCode); } } // At this point we know we are dealing with a configurable product; therefore, // this is the right place to make sure manage stock get turn off. $this->_turnOffManageStock($product); return $data; }
/** * Get childs products * * @param Mage_Catalog_Model_Product $product * @return array Mage_Catalog_Model_Resource_Product */ private static function getChildrenProducts($product, $store = null) { $childrenProducts = array(); // if CONFIGURABLE OR GROUPED OR BUNDLE if ($product->getData('type_id') == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || $product->isSuper()) { if ($typeInstance = $product->getTypeInstance()) { $requiredChildrenIds = $typeInstance->getChildrenIds($product->getId(), true); if ($requiredChildrenIds) { $childrenIds = array(); foreach ($requiredChildrenIds as $groupedChildrenIds) { $childrenIds = array_merge($childrenIds, $groupedChildrenIds); } if ($childrenIds) { $childrenProducts = self::getProducts($childrenIds, $store, null); } } } } return $childrenProducts; }
/** * Get Options with attached Selections collection * * @param Mage_Catalog_Model_Product $product * @return Mage_Bundle_Model_Mysql4_Option_Collection */ public function getOptions($product) { $product->getTypeInstance()->setStoreFilter($product->getStoreId()); $optionCollection = $product->getTypeInstance()->getOptionsCollection(); $selectionCollection = $product->getTypeInstance()->getSelectionsCollection($product->getTypeInstance()->getOptionsIds()); return $optionCollection->appendSelections($selectionCollection, false, false); }
public function getProductOptions(Mage_Catalog_Model_Product $product) { /** @var Ho_SimpleBundle_Model_Bundle_Product_Type $typeInstance */ $typeInstance = $product->getTypeInstance(true); return $typeInstance->getSelectionsCollection($typeInstance->getOptionsIds($product), $product); }
/** * @param Mage_Catalog_Model_Product $product * @return array */ public function outputData($product) { $data = array(); if ($product->getTypeId() !== Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) { return array(); } $productType = $product->getTypeInstance(true); $productType->setProduct($product); $children = $productType->getChildrenIds($product->getId()); if ($children) { $children = $children[0]; } $associations = $this->_getResource()->getSkuByProductIds($children); $data['associations'] = $associations; $attributesData = $productType->getConfigurableAttributesAsArray(); $priceChanges = array(); foreach ($attributesData as $attributeData) { $options = array(); foreach ($attributeData['values'] as $value) { $options[$value['label']] = floatval($value['pricing_value']) . ($value['is_percent'] ? '%' : ''); } $priceChanges[$attributeData['attribute_code']] = array('label' => $attributeData['label'], 'position' => $attributeData['position'], 'options' => $options); } $data['price_changes'] = $priceChanges; return $data; }
/** * getBundlePrice * * @param mixed $productId * @return string */ public function getBundlePrice($productId) { $bundledProduct = new Mage_Catalog_Model_Product(); $bundledProduct->load($productId); $bundledProductType = $bundledProduct->getTypeInstance(true); $dbSelectionCollection = $bundledProductType->getSelectionsCollection($bundledProductType->getOptionsIds($bundledProduct), $bundledProduct); $bundledPrices = array(); foreach ($dbSelectionCollection as $option) { if ($option->getPrice() != "0.0000") { $bundledPrices[] = $option->getPrice(); } } sort($bundledPrices); $minPrice = $bundledPrices[0]; $maxPriceTmp = array_slice($bundledPrices, -1, 1, false); $maxPrice = $maxPriceTmp[0]; return '<div class="price-box"> <p class="price-from"> <span class="price-label">From:</span> <span class="price">' . round($minPrice, 2) . '</span> </p> <p class="price-to"> <span class="price-label">To:</span> <span class="price">' . round($maxPrice, 2) . '</span> </p> </div>'; }
/** * @param Mage_Catalog_Model_Product $product * @return array */ public function outputData($product) { $data = array(); if ($product->getTypeId() !== 'bundle') { return array(); } $options = $product->getTypeInstance()->getOptionsCollection(); $selectionsCollection = $product->getTypeInstance()->getSelectionsCollection($options->getAllIds()); $options->appendSelections($selectionsCollection, false, true); $optionsData = array(); /** @var $option Mage_Bundle_Model_Option */ foreach ($options as $option) { $selectionsData = array(); $optionSelections = $option->getSelections(); /** @var $selection Mage_Bundle_Model_Selection */ foreach ($optionSelections as $selection) { $selectionsData[] = array('sku' => $selection->getSku(), 'price' => $selection->getSelectionPriceValue() . ($selection->getSelectionPriceType() ? '%' : ''), 'default_qty' => $selection->getSelectionQty(), 'selection_can_change_qty' => $selection->getSelectionCanChangeQty(), 'is_default' => $selection->getIsDefault(), 'position' => $selection->getPosition()); } $optionsData[] = array('type' => $option->getType(), 'title' => $option->getDefaultTitle(), 'required' => $option->getRequired(), 'position' => $option->getPosition(), 'bundle_selections' => $selectionsData); } $data['bundle_options'] = $optionsData; return $data; }
/** * Filter out attributes which are used in configurable product * * @param array $attrs List of attributes to filter * @param Mage_Catalog_Model_Product $product Configurable product * @return array List of attributes */ protected function _removeConfigurableAttrs($attrs, $product) { $_attrs = ($_attrs = $product->getConfigurableAttributesData()) !== null ? $_attrs : $product->getTypeInstance()->getConfigurableAttributesAsArray(); foreach ($_attrs as $_attr) { unset($attrs[$_attr['attribute_code']]); } return $attrs; }
public function createConfigurableProduct(&$item, $asid) { $attributeSetModel = Mage::getModel('eav/entity_attribute_set'); $attributeSetModel->load($asid); $attributeSetModel = $attributeSetModel->getData(); if (count($attributeSetModel) > 0) { $p_status = (string) $item->isActive == 'Y' ? 1 : 2; $p_taxclass = (string) $item->isTaxable == 'Y' ? 2 : 0; $product = new Mage_Catalog_Model_Product(); $product->setTypeId('configurable'); $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); //New and created data code start $format = 'Y-m-d H:i:s'; $catalogNewproductDays = Mage::getStoreConfig('catalog/newproduct/days', Mage::app()->getStore()); if (!empty($catalogNewproductDays) && $catalogNewproductDays >= 0) { $currenDateTime = date("Y-m-d H:i:s", Mage::getModel('core/date')->timestamp(time())); $new_from_date = date($format, strtotime('1 days' . $currenDateTime)); $new_to_date = date($format, strtotime($catalogNewproductDays . ' days' . $new_from_date)); $product->setNewsFromDate($new_from_date); $product->setNewsToDate($new_to_date); } if ($product->getCreatedTime == NULL || $product->getUpdateTime() == NULL) { $product->setCreatedTime($currenDateTime)->setUpdateTime($currenDateTime); } //New and created data code end $product->setSku((string) $item->id); //Product custom id $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); $product->setStoreIDs(array($this->_store_id)); // Default store id . $product->setAttributeSetId($asid); $product->setData('name', (string) $item->name); $product->setPrice((double) $item->price); $splAmt = (array) $item->specialPrice->amount; if (isset($item->specialPrice->amount) && $item->specialPrice->amount != NULL) { if (!empty($splAmt)) { $product->setSpecialPrice((double) $item->specialPrice->amount); } //special price in form 11.22 } $fromDate = (array) $item->specialPrice->fromDateTime; if (isset($item->specialPrice->fromDateTime) && $item->specialPrice->fromDateTime != NULL) { if (!empty($fromDate)) { $product->setSpecialFromDate(Mage::helper('customimport')->getCurrentLocaleDateTime($item->specialPrice->fromDateTime)); } //special price from (MM-DD-YYYY) } $toDate = (array) $item->specialPrice->toDateTime; if (isset($item->specialPrice->toDateTime) && $item->specialPrice->toDateTime != NULL) { if (!empty($toDate)) { $product->setSpecialToDate(Mage::helper('customimport')->getCurrentLocaleDateTime($item->specialPrice->toDateTime)); } //special price to (MM-DD-YYYY) } $product->setWeight((double) $item->weight); $product->setStatus($p_status); $product->setTaxClassId($p_taxclass); $product->setDescription((string) $item->longDescription); $product->setShortDescription((string) $item->shortDescription); $product->setMetaTitle((string) $item->pageTitle); $product->setMetaKeyword((string) $item->metaKeywords); $product->setMetaDescription((string) $item->metaDescription); $product->setExternalImage((string) $item->originalImageUrl); $product->setExternalSmallImage((string) $item->largeImageUrl); $product->setExternalThumbnail((string) $item->smallImageUrl); $attributeValues = $item->attributeValues; $attributeOcuurance = array(); //stores no. of occurance for all attributes $configAttributeValue = array(); // will use to take value of attributes that ocuures once $i = 1; foreach ($attributeValues->attribute as $attr) { if (array_key_exists((string) $attr->id, $attributeOcuurance)) { $attributeOcuurance[(string) $attr->id] = (int) $attributeOcuurance[(string) $attr->id] + 1; } else { $attributeOcuurance[(string) $attr->id] = $i; $configAttributeValue[(string) $attr->id][] = (string) $attr->valueDefId; $configAttributeValue[(string) $attr->id][] = (string) $attr->value; } } $superattribute_array = array(); // attributes with multiple occurances $config_attribute_array = array(); //attributes with single occurance foreach ($attributeOcuurance as $key => $val) { if ($val > 1) { $superattribute_array[] = $key; } else { $config_attribute_array[] = $key; } } $attributes_array = array(); if (count($superattribute_array) > 0) { $super_attribute_created = $this->makeAttributeConfigurable($superattribute_array); if ($super_attribute_created) { foreach ($superattribute_array as $attr) { $attributes_array[] = $attr; // contains attribute codes } $ProductAttributeIds = array(); // array stores only super attribute id's $attribute_detail = array(); // stores super attribute's detail $attrnum = 0; foreach ($attributes_array as $attribute_code) { $model = Mage::getModel('catalog/resource_eav_attribute'); $attr = $model->loadByCode('catalog_product', $attribute_code); $attr_id = $attr->getAttributeId(); if (!$attr_id) { $this->customHelper->reportError($this->customHelper->__('Attribute %s is not available in magento. Hence skipping product # %s', $attribute_code, $item->id)); return; } $ProductAttributeIds[] = $attr_id; $attribute_label = $attr->getFrontendLabel(); $attr_detail = array('id' => NULL, 'label' => "{$attribute_label}", 'attribute_id' => $attr_id, 'attribute_code' => "{$attribute_code}", 'frontend_label' => "{$attribute_label}", 'html_id' => "config_super_product__attribute_{$attrnum}"); $attribute_detail[] = $attr_detail; $attrnum++; } $product->getTypeInstance()->setUsedProductAttributeIds($ProductAttributeIds); $product->setConfigurableAttributesData($attribute_detail); $product->setCanSaveConfigurableAttributes(1); foreach ($config_attribute_array as $attr) { $model = Mage::getModel('catalog/resource_eav_attribute'); $loadedattr = $model->loadByCode('catalog_product', $attr); $attr_id = $loadedattr->getAttributeId(); // attribute id of magento if (!$attr_id) { $this->customHelper->reportError($this->customHelper->__('Attribute %s is not available in magento. Hence skipping product # %s', $attr, $item->id)); return; } else { $attr_type = $loadedattr->getFrontendInput(); if ($attr_type == 'select' || $attr_type == 'multiselect') { $external_id = $configAttributeValue[$attr][0]; // valueDefId from XML for an attribute $mapObj = Mage::getModel('customimport/customimport'); $option_id = $mapObj->isOptionExistsInAttribute($external_id, $attr_id); if ($option_id) { $product->setData($attr, $option_id); } else { $this->customHelper->reportError($this->customHelper->__('Attribute %s has an undefined option value %s. Hence skipping product # %s', $attr, $external_id, $item->id)); return; } } elseif ($attr_type == 'text' || $attr_type == 'textarea') { $attr_value = $configAttributeValue[$attr][1]; $product->setData($attr, $attr_value); } elseif ($attr_type == 'boolean') { $optVal = Mage::getSingleton('customimport/customimport')->getOptVal($configAttributeValue[$attr][0]); if (strtolower($optVal->getValue()) == 'y' || strtolower($optVal->getValue()) == 'yes') { $attOptVal = 1; } else { $attOptVal = 0; } $product->setData($attr, $attOptVal); } } } try { Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); $product->save(); $stockItem = Mage::getModel('cataloginventory/stock_item'); $stockItem->assignProduct($product); $stockItem->setData('stock_id', (int) 1); $stockItem->setData('use_config_manage_stock', (int) 1); $stockItem->setData('min_qty', (int) 0); $stockItem->setData('is_decimal_divided', (int) 0); $stockItem->setData('qty', (int) 0); $stockItem->setData('use_config_min_qty', 1); $stockItem->setData('use_config_backorders', 1); $stockItem->setData('min_sale_qty', 1); $stockItem->setData('use_config_min_sale_qty', 1); $stockItem->setData('use_config_max_sale_qty', 1); $stockItem->setData('is_in_stock', 1); $stockItem->setData('use_config_notify_stock_qty', 1); // Manage Stock $inventory = $item->inventory; $manageItem = (string) strtoupper($inventory->manageStock); if ($manageItem == 'N') { $stockItem->setData('use_config_manage_stock', 0); $stockItem->setData('manage_stock', 0); } $stockItem->save(); $stockStatus = Mage::getModel('cataloginventory/stock_status'); $stockStatus->assignProduct($product); $stockStatus->saveProductStatus($product->getId(), 1); $this->_created_num++; } catch (Exception $e) { $this->customHelper->writeCustomLog('<span style="color:red;">' . $e->getMessage() . '</span>', $this->logPath); $this->customHelper->sendLogEmail($this->logPath); } } else { $this->customHelper->reportError($this->customHelper->__('Could not create super attribute for configurable product from %s. Hence skipped product # %s', array_values($superattribute_array), $item->id)); } } else { $this->customHelper->reportError($this->customHelper->__('No super attributes defined for configurable product. Hence skipped product # %s', $item->id)); } } else { $this->customHelper->reportError($this->customHelper->__('Attribute set ID # %s is missing. Hence skipped product # %s', $asid, $item->id)); } }
public function isProductHasOptions(Mage_Catalog_Model_Product $product) { $groupedChilds = $bundleChilds = $optionCollection = $storeCreditOptions = array(); $productTypeInstance = $product->getTypeInstance(true); $hasOption = $productTypeInstance->hasOptions($product); if ($hasOption == true) { $optionCollection = Mage::getModel('catalog/product_option')->getProductOptionCollection($product); } $configurableOptions = $this->getConfigurableOptions($product); if ($product->getTypeId() == 'grouped') { $groupedChilds = $this->getGroupedChilds($product); } if ($product->getTypeId() == 'bundle') { $bundleChilds = $this->getBundleChilds($product); } if ($product->getTypeId() == 'customercredit') { $storeCreditOptions = $this->getStoreCreditOptions($product); } return count($storeCreditOptions) > 0 || count($bundleChilds) > 0 || count($groupedChilds) > 0 || count($optionCollection) > 0 || $configurableOptions != '' && count($configurableOptions) > 1 ? true : false; }