/** * @param \Magento\Catalog\Model\Product $product * @param int|string $customerGroupId * @param int $qty * @param int $websiteId * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\CouldNotSaveException * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function removeTierPrice(\Magento\Catalog\Model\Product $product, $customerGroupId, $qty, $websiteId) { $prices = $product->getData('tier_price'); // verify if price exist if ($prices === null) { throw new NoSuchEntityException(__('This product doesn\'t have tier price')); } $tierPricesQty = count($prices); foreach ($prices as $key => $tierPrice) { if ($customerGroupId == 'all' && $tierPrice['price_qty'] == $qty && $tierPrice['all_groups'] == 1 && intval($tierPrice['website_id']) === intval($websiteId)) { unset($prices[$key]); } elseif ($tierPrice['price_qty'] == $qty && $tierPrice['cust_group'] == $customerGroupId && intval($tierPrice['website_id']) === intval($websiteId)) { unset($prices[$key]); } } if ($tierPricesQty == count($prices)) { throw new NoSuchEntityException(__('Product hasn\'t group price with such data: customerGroupId = \'%1\'' . ', website = %2, qty = %3', [$customerGroupId, $websiteId, $qty])); } $product->setData('tier_price', $prices); try { $this->productRepository->save($product); } catch (\Exception $exception) { throw new CouldNotSaveException(__('Invalid data provided for tier_price')); } }
/** * @magentoDataFixture Magento/Bundle/_files/product.php * @magentoDbIsolation enabled */ public function testSaveFailure() { $this->markTestSkipped("When MAGETWO-36510 is fixed, need to change Dbisolation to disabled"); $bundleProductSku = 'bundle-product'; $product = $this->productRepository->get($bundleProductSku); $bundleExtensionAttributes = $product->getExtensionAttributes()->getBundleProductOptions(); $bundleOption = $bundleExtensionAttributes[0]; $this->assertEquals(true, $bundleOption->getRequired()); $bundleOption->setRequired(false); //set an incorrect option id to trigger exception $bundleOption->setOptionId(-1); $description = "hello"; $product->setDescription($description); $product->getExtensionAttributes()->setBundleProductOptions([$bundleOption]); $caughtException = false; try { $this->productRepository->save($product); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $caughtException = true; } $this->assertTrue($caughtException); /** @var \Magento\Catalog\Model\Product $product */ $product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Model\\Product')->load($product->getId()); $this->assertEquals(null, $product->getDescription()); }
/** * {@inheritdoc} */ public function setProductLinks($sku, $type, array $items) { $linkTypes = $this->linkTypeProvider->getLinkTypes(); if (!isset($linkTypes[$type])) { throw new NoSuchEntityException(__('Provided link type "%1" does not exist', $type)); } $product = $this->productRepository->get($sku); // Replace only links of the specified type $existingLinks = $product->getProductLinks(); $newLinks = []; if (!empty($existingLinks)) { foreach ($existingLinks as $link) { if ($link->getLinkType() != $type) { $newLinks[] = $link; } } $newLinks = array_merge($newLinks, $items); } else { $newLinks = $items; } $product->setProductLinks($newLinks); try { $this->productRepository->save($product); } catch (\Exception $exception) { throw new CouldNotSaveException(__('Invalid data provided for linked products')); } return true; }
/** * Generates child products for configurable product * * @param \Magento\Catalog\Api\Data\ProductAttributeInterface $configurableAttribute * @return array * @throws \Exception */ protected function createConfigurableChildren($configurableAttribute) { $availableOptions = $configurableAttribute->getOptions(); /* Not sure why the zero index has no value for all attributes. Maybe will be fixed in next Magento versions */ unset($availableOptions[0]); if (!count($availableOptions) > 0) { throw new \Exception('The selected configurable attribute has no values'); } // Create child simple products $availableProductsCount = $this->getCount() - $this->processedProducts - 1; if ($availableProductsCount >= self::CONFIGURABLE_CHILD_LIMIT) { $childrenLimit = self::CONFIGURABLE_CHILD_LIMIT; } else { $childrenLimit = $availableProductsCount; } if ($childrenLimit > count($availableOptions)) { $childrenLimit = count($availableOptions); } $childrenCount = rand(1, $childrenLimit); $childProductsIds = $configurableOptionsValues = []; for ($optCount = 0; $optCount < $childrenCount; $optCount++) { $product = $this->createSimpleProduct(true, true); $currentOptionId = array_rand($availableOptions); $optValueId = $availableOptions[$currentOptionId]->getValue(); unset($availableOptions[$currentOptionId]); $product->setCustomAttribute($configurableAttribute->getAttributeCode(), $optValueId); $optionValue = $this->optionValue; $optionValue->setValueIndex($optValueId); $configurableOptionsValues[] = $optionValue; $product = $this->productRepository->save($product); $childProductsIds[] = $product->getId(); } return ['child_products_ids' => $childProductsIds, 'configurable_options_values' => $configurableOptionsValues]; }
/** * @param string $sku */ public function enableProductWithSku($sku) { $this->validateSku($sku); $product = $this->productRepository->get($sku); if ($product->getStatus() == ProductStatus::STATUS_ENABLED) { throw new \RuntimeException(sprintf('The product with the SKU "%s" already is enabled', $sku)); } $product->setStatus(ProductStatus::STATUS_ENABLED); $this->productRepository->save($product); }
/** * @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php * @magentoAppIsolation enabled */ public function testSaveProductRelationsNoChildren() { $childrenIds = $this->product->getTypeInstance()->getChildrenIds($this->product->getId()); self::assertNotEmpty(reset($childrenIds)); $product = $this->productRepository->getById($this->product->getId(), true); $extensionAttributes = $product->getExtensionAttributes(); $extensionAttributes->setConfigurableProductLinks([]); $product->setExtensionAttributes($extensionAttributes); $this->productRepository->save($product); self::assertEquals([[]], $this->model->getChildrenIds($this->product->getId())); }
/** * Create simple product. * * @param int $mageId * @param string $name * @param bool $isActive * @param double $priceWholesale * @param double $weight */ public function update($mageId, $name, $isActive, $priceWholesale, $weight) { $this->_logger->debug("Update product (id: {$mageId}; name: {$name}; active: {$isActive}; price: {$priceWholesale}; weight: {$weight}.)"); /** @var \Magento\Catalog\Api\Data\ProductInterface $product */ $product = $this->_mageRepoProd->getById($mageId); // SKU should not be changed $product->setName($name); $status = $this->_getStatus($isActive); $product->setStatus($status); $product->setPrice($priceWholesale); $product->setWeight($weight); $this->_mageRepoProd->save($product); }
/** * {@inheritdoc} */ public function remove($sku, $entryId) { $product = $this->productRepository->get($sku); /** @var $productMediaGallery \Magento\Catalog\Model\Product\Attribute\Backend\Media */ $productMediaGallery = $this->getGalleryAttributeBackend($product); $filePath = $this->entryResolver->getEntryFilePathById($product, $entryId); if ($filePath === null) { throw new NoSuchEntityException(__('There is no image with provided ID.')); } $productMediaGallery->removeImage($product, $filePath); $this->productRepository->save($product); return true; }
/** * @param string $sku */ public function enableProductWithSku($sku) { $this->validateSku($sku); try { $product = $this->productRepository->get($sku); if ($product->getStatus() == ProductStatus::STATUS_ENABLED) { throw new ProductAlreadyEnabledException(sprintf('The product "%s" already is enabled', $sku)); } $product->setStatus(ProductStatus::STATUS_ENABLED); $this->productRepository->save($product); } catch (NoSuchEntityException $exception) { throw new ProductStatusAdapterException($exception->getMessage()); } }
/** * {@inheritdoc} */ public function deleteByIdentifier($sku, $optionId) { $product = $this->productRepository->get($sku, true); $options = $product->getOptions(); $option = $product->getOptionById($optionId); if ($option === null) { throw NoSuchEntityException::singleField('optionId', $optionId); } unset($options[$optionId]); try { $this->delete($option); if (empty($options)) { $this->productRepository->save($product); } } catch (\Exception $e) { throw new CouldNotSaveException(__('Could not remove custom option')); } return true; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function add($sku, $customerGroupId, $price, $qty) { if (!\Zend_Validate::is($price, 'Float') || $price <= 0 || !\Zend_Validate::is($qty, 'Float') || $qty <= 0) { throw new InputException(__('Please provide valid data')); } $product = $this->productRepository->get($sku, ['edit_mode' => true]); $tierPrices = $product->getData('tier_price'); $websiteIdentifier = 0; $value = $this->config->getValue('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE); if ($value != 0) { $websiteIdentifier = $this->storeManager->getWebsite()->getId(); } $found = false; foreach ($tierPrices as &$item) { if ('all' == $customerGroupId) { $isGroupValid = $item['all_groups'] == 1; } else { $isGroupValid = $item['cust_group'] == $customerGroupId; } if ($isGroupValid && $item['website_id'] == $websiteIdentifier && $item['price_qty'] == $qty) { $item['price'] = $price; $found = true; break; } } if (!$found) { $mappedCustomerGroupId = 'all' == $customerGroupId ? $this->groupManagement->getAllCustomersGroup()->getId() : $this->groupRepository->getById($customerGroupId)->getId(); $tierPrices[] = ['cust_group' => $mappedCustomerGroupId, 'price' => $price, 'website_price' => $price, 'website_id' => $websiteIdentifier, 'price_qty' => $qty]; } $product->setData('tier_price', $tierPrices); $errors = $product->validate(); if (is_array($errors) && count($errors)) { $errorAttributeCodes = implode(', ', array_keys($errors)); throw new InputException(__('Values of following attributes are invalid: %1', $errorAttributeCodes)); } try { $this->productRepository->save($product); } catch (\Exception $e) { throw new CouldNotSaveException(__('Could not save group price')); } return true; }
/** * {@inheritdoc} */ public function remove($sku, $entryId) { $product = $this->productRepository->get($sku); $existingMediaGalleryEntries = $product->getMediaGalleryEntries(); if ($existingMediaGalleryEntries == null) { throw new NoSuchEntityException(__('There is no image with provided ID.')); } $found = false; foreach ($existingMediaGalleryEntries as $key => $entry) { if ($entry->getId() == $entryId) { unset($existingMediaGalleryEntries[$key]); $found = true; break; } } if (!$found) { throw new NoSuchEntityException(__('There is no image with provided ID.')); } $product->setMediaGalleryEntries($existingMediaGalleryEntries); $this->productRepository->save($product); return true; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function add($sku, $customerGroupId, $price) { if (!\Zend_Validate::is($price, 'Float') || $price <= 0 || !\Zend_Validate::is($price, 'Float')) { throw new InputException(__('Please provide valid data')); } $customerGroup = $this->groupRepository->getById($customerGroupId); $product = $this->productRepository->get($sku, true); $groupPrices = $product->getData('group_price'); $websiteIdentifier = 0; $value = $this->config->getValue('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE); if ($value != 0) { $websiteIdentifier = $this->storeManager->getWebsite()->getId(); } $found = false; foreach ($groupPrices as &$currentPrice) { if (intval($currentPrice['cust_group']) === $customerGroupId && intval($currentPrice['website_id']) === intval($websiteIdentifier)) { $currentPrice['price'] = $price; $found = true; break; } } if (!$found) { $groupPrices[] = ['cust_group' => $customerGroup->getId(), 'website_id' => $websiteIdentifier, 'price' => $price]; } $product->setData('group_price', $groupPrices); $errors = $product->validate(); if (is_array($errors) && count($errors)) { $errorAttributeCodes = implode(', ', array_keys($errors)); throw new InputException(__('Values of following attributes are invalid: %1', $errorAttributeCodes)); } try { $this->productRepository->save($product); } catch (\Exception $e) { throw new CouldNotSaveException(__('Could not save group price')); } return true; }