/**
  * @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());
 }
Example #2
0
 /**
  * @param string $entityType
  * @param object $entity
  * @return object
  * @throws CouldNotSaveException
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute($entityType, $entity)
 {
     /**
      * @var $entity \Magento\Catalog\Api\Data\ProductLinkInterface
      */
     $linkedProduct = $this->productRepository->get($entity->getLinkedProductSku());
     $product = $this->productRepository->get($entity->getSku());
     $links = [];
     $extensions = $this->dataObjectProcessor->buildOutputDataArray($entity->getExtensionAttributes(), 'Magento\\Catalog\\Api\\Data\\ProductLinkExtensionInterface');
     $extensions = is_array($extensions) ? $extensions : [];
     $data = $entity->__toArray();
     foreach ($extensions as $attributeCode => $attribute) {
         $data[$attributeCode] = $attribute;
     }
     unset($data['extension_attributes']);
     $data['product_id'] = $linkedProduct->getId();
     $links[$linkedProduct->getId()] = $data;
     try {
         $linkTypesToId = $this->linkTypeProvider->getLinkTypes();
         $prodyctHydrator = $this->metadataPool->getHydrator(ProductInterface::class);
         $productData = $prodyctHydrator->extract($product);
         $this->linkResource->saveProductLinks($productData[$this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()], $links, $linkTypesToId[$entity->getLinkType()]);
     } catch (\Exception $exception) {
         throw new CouldNotSaveException(__('Invalid data provided for linked products'));
     }
     return $entity;
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function save(\Magento\Quote\Api\Data\CartItemInterface $cartItem)
 {
     $qty = $cartItem->getQty();
     if (!is_numeric($qty) || $qty <= 0) {
         throw InputException::invalidFieldValue('qty', $qty);
     }
     $cartId = $cartItem->getQuoteId();
     /** @var \Magento\Quote\Model\Quote $quote */
     $quote = $this->quoteRepository->getActive($cartId);
     $itemId = $cartItem->getItemId();
     try {
         /** update item qty */
         if (isset($itemId)) {
             $cartItem = $quote->getItemById($itemId);
             if (!$cartItem) {
                 throw new NoSuchEntityException(__('Cart %1 doesn\'t contain item  %2', $cartId, $itemId));
             }
             $product = $this->productRepository->get($cartItem->getSku());
             $cartItem->setData('qty', $qty);
         } else {
             $product = $this->productRepository->get($cartItem->getSku());
             $quote->addProduct($product, $qty);
         }
         $this->quoteRepository->save($quote->collectTotals());
     } catch (\Exception $e) {
         if ($e instanceof NoSuchEntityException) {
             throw $e;
         }
         throw new CouldNotSaveException(__('Could not save quote'));
     }
     return $quote->getItemByProduct($product);
 }
 /**
  * Cached access to product in DB.
  *
  * @param string $sku
  * @return \Magento\Catalog\Api\Data\ProductInterface
  */
 public function _getProductBySku($sku)
 {
     if (!isset($this->_cacheProducts[$sku])) {
         $this->_cacheProducts[$sku] = $this->_repoCatProd->get($sku);
     }
     return $this->_cacheProducts[$sku];
 }
Example #5
0
 /**
  * {@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;
 }
 /**
  * {@inheritdoc}
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function save($productSku, SampleContentInterface $sampleContent, $sampleId = null, $isGlobalScopeContent = false)
 {
     $product = $this->productRepository->get($productSku, true);
     if ($sampleId) {
         /** @var $sample \Magento\Downloadable\Model\Sample */
         $sample = $this->sampleFactory->create()->load($sampleId);
         if (!$sample->getId()) {
             throw new NoSuchEntityException(__('There is no downloadable sample with provided ID.'));
         }
         if ($sample->getProductId() != $product->getId()) {
             throw new InputException(__('Provided downloadable sample is not related to given product.'));
         }
         if (!$this->contentValidator->isValid($sampleContent)) {
             throw new InputException(__('Provided sample information is invalid.'));
         }
         if ($isGlobalScopeContent) {
             $product->setStoreId(0);
         }
         $title = $sampleContent->getTitle();
         if (empty($title)) {
             if ($isGlobalScopeContent) {
                 throw new InputException(__('Sample title cannot be empty.'));
             }
             // use title from GLOBAL scope
             $sample->setTitle(null);
         } else {
             $sample->setTitle($sampleContent->getTitle());
         }
         $sample->setProductId($product->getId())->setStoreId($product->getStoreId())->setSortOrder($sampleContent->getSortOrder())->save();
         return $sample->getId();
     } else {
         if ($product->getTypeId() !== \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) {
             throw new InputException(__('Product type of the product must be \'downloadable\'.'));
         }
         if (!$this->contentValidator->isValid($sampleContent)) {
             throw new InputException(__('Provided sample information is invalid.'));
         }
         if (!in_array($sampleContent->getSampleType(), ['url', 'file'])) {
             throw new InputException(__('Invalid sample type.'));
         }
         $title = $sampleContent->getTitle();
         if (empty($title)) {
             throw new InputException(__('Sample title cannot be empty.'));
         }
         $sampleData = ['sample_id' => 0, 'is_delete' => 0, 'type' => $sampleContent->getSampleType(), 'sort_order' => $sampleContent->getSortOrder(), 'title' => $sampleContent->getTitle()];
         if ($sampleContent->getSampleType() == 'file') {
             $sampleData['file'] = $this->jsonEncoder->encode([$this->fileContentUploader->upload($sampleContent->getSampleFile(), 'sample')]);
         } else {
             $sampleData['sample_url'] = $sampleContent->getSampleUrl();
         }
         $downloadableData = ['sample' => [$sampleData]];
         $product->setDownloadableData($downloadableData);
         if ($isGlobalScopeContent) {
             $product->setStoreId(0);
         }
         $product->save();
         return $product->getLastAddedSampleId();
     }
 }
 /**
  * {@inheritdoc}
  */
 public function save(\Magento\Bundle\Api\Data\OptionInterface $option)
 {
     $product = $this->productRepository->get($option->getSku(), true);
     if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
         throw new InputException(__('Only implemented for bundle product'));
     }
     return $this->optionRepository->save($product, $option);
 }
 /**
  * {@inheritdoc}
  */
 public function deleteById($sku, $websiteId)
 {
     $product = $this->productRepository->get($sku);
     $product->setWebsiteIds(array_diff($product->getWebsiteIds(), [$websiteId]));
     try {
         $product->save();
     } catch (\Exception $e) {
         throw new CouldNotSaveException(__('Could not save product "%1" with websites %2', $product->getId(), implode(', ', $product->getWebsiteIds())), $e);
     }
     return true;
 }
 /**
  * @param CartInterface $quote
  * @param CartItemInterface $item
  * @return CartItemInterface
  * @throws CouldNotSaveException
  * @throws InputException
  * @throws LocalizedException
  * @throws NoSuchEntityException
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function save(CartInterface $quote, CartItemInterface $item)
 {
     /** @var \Magento\Quote\Model\Quote $quote */
     $qty = $item->getQty();
     if (!is_numeric($qty) || $qty <= 0) {
         throw InputException::invalidFieldValue('qty', $qty);
     }
     $cartId = $item->getQuoteId();
     $itemId = $item->getItemId();
     try {
         /** Update existing item */
         if (isset($itemId)) {
             $currentItem = $quote->getItemById($itemId);
             if (!$currentItem) {
                 throw new NoSuchEntityException(__('Cart %1 does not contain item %2', $cartId, $itemId));
             }
             $productType = $currentItem->getProduct()->getTypeId();
             $buyRequestData = $this->cartItemOptionProcessor->getBuyRequest($productType, $item);
             if (is_object($buyRequestData)) {
                 /** Update item product options */
                 $item = $quote->updateItem($itemId, $buyRequestData);
             } else {
                 if ($item->getQty() !== $currentItem->getQty()) {
                     $currentItem->setQty($qty);
                 }
             }
         } else {
             /** add new item to shopping cart */
             $product = $this->productRepository->get($item->getSku());
             $productType = $product->getTypeId();
             $item = $quote->addProduct($product, $this->cartItemOptionProcessor->getBuyRequest($productType, $item));
             if (is_string($item)) {
                 throw new LocalizedException(__($item));
             }
         }
     } catch (NoSuchEntityException $e) {
         throw $e;
     } catch (LocalizedException $e) {
         throw $e;
     } catch (\Exception $e) {
         throw new CouldNotSaveException(__('Could not save quote'));
     }
     $itemId = $item->getId();
     foreach ($quote->getAllItems() as $quoteItem) {
         /** @var \Magento\Quote\Model\Quote\Item $quoteItem */
         if ($itemId == $quoteItem->getId()) {
             $item = $this->cartItemOptionProcessor->addProductOptions($productType, $quoteItem);
             return $this->cartItemOptionProcessor->applyCustomOptions($item);
         }
     }
     throw new CouldNotSaveException(__('Could not save quote'));
 }
Example #10
0
 protected function setUp()
 {
     $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
     $this->productRepository = $this->objectManager->create('Magento\\Catalog\\Api\\ProductRepositoryInterface');
     try {
         $this->product = $this->productRepository->get('simple');
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         $this->product = $this->productRepository->get('simple_dropdown_option');
     }
     $this->objectManager->get('Magento\\Framework\\Registry')->unregister('current_product');
     $this->objectManager->get('Magento\\Framework\\Registry')->register('current_product', $this->product);
     $this->block = $this->objectManager->get('Magento\\Framework\\View\\LayoutInterface')->createBlock('Magento\\Catalog\\Block\\Product\\View\\Options');
 }
 /**
  * @param \Magento\Catalog\Api\ProductRepositoryInterface $subject
  * @param callable $proceed
  * @param \Magento\Catalog\Api\Data\ProductInterface $product
  * @param bool $saveOptions
  * @return \Magento\Catalog\Api\Data\ProductInterface
  * @throws \Magento\Framework\Exception\CouldNotSaveException
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundSave(\Magento\Catalog\Api\ProductRepositoryInterface $subject, \Closure $proceed, \Magento\Catalog\Api\Data\ProductInterface $product, $saveOptions = false)
 {
     /** @var \Magento\Catalog\Api\Data\ProductInterface $result */
     $result = $proceed($product, $saveOptions);
     if ($product->getTypeId() != \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
         return $result;
     }
     $extendedAttributes = $product->getExtensionAttributes();
     if ($extendedAttributes === null) {
         return $result;
     }
     $configurableProductOptions = $extendedAttributes->getConfigurableProductOptions();
     $configurableProductLinks = $extendedAttributes->getConfigurableProductLinks();
     if ($configurableProductOptions === null && $configurableProductLinks === null) {
         return $result;
     }
     if ($configurableProductOptions !== null) {
         $this->saveConfigurableProductOptions($result, $configurableProductOptions);
         $result->getTypeInstance()->resetConfigurableAttributes($result);
     }
     if ($configurableProductLinks !== null) {
         $this->saveConfigurableProductLinks($result, $configurableProductLinks);
     }
     return $subject->get($result->getSku(), false, $result->getStoreId(), true);
 }
Example #12
0
 /**
  * {@inheritdoc}
  */
 public function modifyData(array $data)
 {
     /** @var \Magento\Catalog\Model\Product $product */
     $product = $this->locator->getProduct();
     $productId = $product->getId();
     if (!$productId) {
         return $data;
     }
     $priceModifier = $this->getPriceModifier();
     /**
      * Set field name for modifier
      */
     $priceModifier->setData('name', 'price');
     foreach ($this->getDataScopes() as $dataScope) {
         $data[$productId]['links'][$dataScope] = [];
         foreach ($this->productLinkRepository->getList($product) as $linkItem) {
             if ($linkItem->getLinkType() !== $dataScope) {
                 continue;
             }
             /** @var \Magento\Catalog\Model\Product $linkedProduct */
             $linkedProduct = $this->productRepository->get($linkItem->getLinkedProductSku(), false, $this->locator->getStore()->getId());
             $data[$productId]['links'][$dataScope][] = $this->fillData($linkedProduct, $linkItem);
         }
         if (!empty($data[$productId]['links'][$dataScope])) {
             $dataMap = $priceModifier->prepareDataSource(['data' => ['items' => $data[$productId]['links'][$dataScope]]]);
             $data[$productId]['links'][$dataScope] = $dataMap['data']['items'];
         }
     }
     $data[$productId][self::DATA_SOURCE_DEFAULT]['current_product_id'] = $productId;
     $data[$productId][self::DATA_SOURCE_DEFAULT]['current_store_id'] = $this->locator->getStore()->getId();
     return $data;
 }
Example #13
0
 /**
  * {@inheritdoc}
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function modifyData(array $data)
 {
     /** @var \Magento\Catalog\Api\Data\ProductInterface $product */
     $product = $this->locator->getProduct();
     $modelId = $product->getId();
     $isBundleProduct = $product->getTypeId() === Type::TYPE_CODE;
     if ($isBundleProduct && $modelId) {
         $data[$modelId][BundlePanel::CODE_BUNDLE_OPTIONS][BundlePanel::CODE_BUNDLE_OPTIONS] = [];
         /** @var \Magento\Bundle\Api\Data\OptionInterface $option */
         foreach ($this->optionsRepository->getList($product->getSku()) as $option) {
             $selections = [];
             /** @var \Magento\Bundle\Api\Data\LinkInterface $productLink */
             foreach ($option->getProductLinks() as $productLink) {
                 $linkedProduct = $this->productRepository->get($productLink->getSku());
                 $integerQty = 1;
                 if ($linkedProduct->getExtensionAttributes()->getStockItem()) {
                     if ($linkedProduct->getExtensionAttributes()->getStockItem()->getIsQtyDecimal()) {
                         $integerQty = 0;
                     }
                 }
                 $selections[] = ['selection_id' => $productLink->getId(), 'option_id' => $productLink->getOptionId(), 'product_id' => $linkedProduct->getId(), 'name' => $linkedProduct->getName(), 'sku' => $linkedProduct->getSku(), 'is_default' => $productLink->getIsDefault() ? '1' : '0', 'selection_price_value' => $productLink->getPrice(), 'selection_price_type' => $productLink->getPriceType(), 'selection_qty' => (bool) $integerQty ? (int) $productLink->getQty() : $productLink->getQty(), 'selection_can_change_qty' => $productLink->getCanChangeQuantity(), 'selection_qty_is_integer' => (bool) $integerQty, 'position' => $productLink->getPosition(), 'delete' => ''];
             }
             $data[$modelId][BundlePanel::CODE_BUNDLE_OPTIONS][BundlePanel::CODE_BUNDLE_OPTIONS][] = ['position' => $option->getPosition(), 'option_id' => $option->getOptionId(), 'title' => $option->getTitle(), 'default_title' => $option->getDefaultTitle(), 'type' => $option->getType(), 'required' => $option->getRequired() ? '1' : '0', 'bundle_selections' => $selections];
         }
     }
     return $data;
 }
 /**
  * @param ProductRepositoryInterface $subject
  * @param callable $proceed
  * @param ProductInterface $product
  * @param bool $saveOptions
  * @return ProductInterface
  * @throws CouldNotSaveException
  * @throws InputException
  *
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundSave(ProductRepositoryInterface $subject, \Closure $proceed, ProductInterface $product, $saveOptions = false)
 {
     /** @var ProductInterface $result */
     $result = $proceed($product, $saveOptions);
     if ($product->getTypeId() !== Configurable::TYPE_CODE) {
         return $result;
     }
     $extensionAttributes = $result->getExtensionAttributes();
     if ($extensionAttributes === null) {
         return $result;
     }
     $configurableLinks = (array) $extensionAttributes->getConfigurableProductLinks();
     $configurableOptions = (array) $extensionAttributes->getConfigurableProductOptions();
     if (empty($configurableLinks) && empty($configurableOptions)) {
         return $result;
     }
     $attributeCodes = [];
     /** @var OptionInterface $configurableOption */
     foreach ($configurableOptions as $configurableOption) {
         $eavAttribute = $this->productAttributeRepository->get($configurableOption->getAttributeId());
         $attributeCode = $eavAttribute->getAttributeCode();
         $attributeCodes[] = $attributeCode;
     }
     $this->validateProductLinks($attributeCodes, $configurableLinks);
     return $subject->get($result->getSku(), false, $result->getStoreId(), true);
 }
Example #15
0
 /**
  * {@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);
     $assignedSkuList = [];
     /** @var \Magento\Catalog\Api\Data\ProductLinkInterface $link */
     foreach ($items as $link) {
         $assignedSkuList[] = $link->getLinkedProductSku();
     }
     $linkedProductIds = $this->productResource->getProductsIdsBySkus($assignedSkuList);
     $links = [];
     /** @var \Magento\Catalog\Api\Data\ProductLinkInterface[] $items*/
     foreach ($items as $link) {
         $data = $link->__toArray();
         $linkedSku = $link->getLinkedProductSku();
         if (!isset($linkedProductIds[$linkedSku])) {
             throw new NoSuchEntityException(__('Product with SKU "%1" does not exist', $linkedSku));
         }
         $data['product_id'] = $linkedProductIds[$linkedSku];
         $links[$linkedProductIds[$linkedSku]] = $data;
     }
     $this->linkInitializer->initializeLinks($product, [$type => $links]);
     try {
         $product->save();
     } catch (\Exception $exception) {
         throw new CouldNotSaveException(__('Invalid data provided for linked products'));
     }
     return true;
 }
 /**
  * {@inheritdoc}
  */
 public function removeChild($sku, $optionId, $childSku)
 {
     $product = $this->productRepository->get($sku);
     if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
         throw new InputException(__('Product with specified sku: %1 is not a bundle product', $sku));
     }
     $excludeSelectionIds = [];
     $usedProductIds = [];
     $removeSelectionIds = [];
     foreach ($this->getOptions($product) as $option) {
         /** @var \Magento\Bundle\Model\Selection $selection */
         foreach ($option->getSelections() as $selection) {
             if (strcasecmp($selection->getSku(), $childSku) == 0 && $selection->getOptionId() == $optionId) {
                 $removeSelectionIds[] = $selection->getSelectionId();
                 continue;
             }
             $excludeSelectionIds[] = $selection->getSelectionId();
             $usedProductIds[] = $selection->getProductId();
         }
     }
     if (empty($removeSelectionIds)) {
         throw new \Magento\Framework\Exception\NoSuchEntityException(__('Requested bundle option product doesn\'t exist'));
     }
     /* @var $resource \Magento\Bundle\Model\Resource\Bundle */
     $resource = $this->bundleFactory->create();
     $resource->dropAllUnneededSelections($product->getId(), $excludeSelectionIds);
     $resource->saveProductRelations($product->getId(), array_unique($usedProductIds));
     return true;
 }
 /**
  * @param \Magento\Catalog\Api\ProductRepositoryInterface $subject
  * @param callable $proceed
  * @param \Magento\Catalog\Api\Data\ProductInterface $product
  * @param bool $saveOptions
  * @return \Magento\Catalog\Api\Data\ProductInterface
  * @throws \Magento\Framework\Exception\CouldNotSaveException
  */
 public function aroundSave(\Magento\Catalog\Api\ProductRepositoryInterface $subject, \Closure $proceed, \Magento\Catalog\Api\Data\ProductInterface $product, $saveOptions = false)
 {
     /** @var \Magento\Catalog\Api\Data\ProductInterface $result */
     $result = $proceed($product, $saveOptions);
     if ($product->getTypeId() != \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) {
         return $result;
     }
     /* @var \Magento\Catalog\Api\Data\ProductExtensionInterface $options */
     $extendedAttributes = $product->getExtensionAttributes();
     if ($extendedAttributes === null) {
         return $result;
     }
     $links = $extendedAttributes->getDownloadableProductLinks();
     $samples = $extendedAttributes->getDownloadableProductSamples();
     if ($links === null && $samples === null) {
         return $result;
     }
     if ($links !== null) {
         $this->saveLinks($result, $links);
     }
     if ($samples !== null) {
         $this->saveSamples($result, $samples);
     }
     return $subject->get($result->getSku(), false, $result->getStoreId(), true);
 }
Example #18
0
 /**
  * Retrieve product instance by sku
  *
  * @param string $sku
  * @return ProductInterface
  * @throws InputException
  */
 private function getProduct($sku)
 {
     $product = $this->productRepository->get($sku);
     if (\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE !== $product->getTypeId()) {
         throw new InputException(__('Only implemented for configurable product: %1', $sku));
     }
     return $product;
 }
 /**
  * @param string $sku
  * @return \Magento\Catalog\Api\Data\ProductInterface
  * @throws \Magento\Framework\Exception\InputException
  */
 private function getProduct($sku)
 {
     $product = $this->productRepository->get($sku);
     if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
         throw new InputException(__('Only implemented for bundle product'));
     }
     return $product;
 }
Example #20
0
 /**
  * @param string $entityType
  * @param object $entity
  * @return object
  * @throws CouldNotDeleteException
  * @throws NoSuchEntityException
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute($entityType, $entity)
 {
     $linkedProduct = $this->productRepository->get($entity->getLinkedProductSku());
     $product = $this->productRepository->get($entity->getSku());
     $linkTypesToId = $this->linkTypeProvider->getLinkTypes();
     $prodyctHydrator = $this->metadataPool->getHydrator(ProductInterface::class);
     $productData = $prodyctHydrator->extract($product);
     $linkId = $this->linkResource->getProductLinkId($productData[$this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()], $linkedProduct->getId(), $linkTypesToId[$entity->getLinkType()]);
     if (!$linkId) {
         throw new NoSuchEntityException(__('Product with SKU %1 is not linked to product with SKU %2', $entity->getLinkedProductSku(), $entity->getSku()));
     }
     try {
         $this->linkResource->deleteProductLink($linkId);
     } catch (\Exception $exception) {
         throw new CouldNotDeleteException(__('Invalid data provided for linked products'));
     }
 }
Example #21
0
 /**
  * {@inheritdoc}
  */
 public function delete(\Magento\Catalog\Api\Data\ProductLinkInterface $entity)
 {
     $linkedProduct = $this->productRepository->get($entity->getLinkedProductSku());
     $product = $this->productRepository->get($entity->getProductSku());
     $links = $this->entityCollectionProvider->getCollection($product, $entity->getLinkType());
     if (!isset($links[$linkedProduct->getId()])) {
         throw new NoSuchEntityException(__('Product with SKU %1 is not linked to product with SKU %2', $entity->getLinkedProductSku(), $entity->getProductSku()));
     }
     //Remove product from the linked product list
     unset($links[$linkedProduct->getId()]);
     $this->linkInitializer->initializeLinks($product, [$entity->getLinkType() => $links]);
     try {
         $product->save();
     } catch (\Exception $exception) {
         throw new CouldNotSaveException(__('Invalid data provided for linked products'));
     }
     return true;
 }
 /**
  * @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);
 }
 /**
  * {@inheritdoc}
  */
 public function deleteByIds($categoryId, $sku)
 {
     $category = $this->categoryRepository->get($categoryId);
     $product = $this->productRepository->get($sku);
     $productPositions = $category->getProductsPosition();
     $productID = $product->getId();
     if (!isset($productPositions[$productID])) {
         throw new InputException(__('Category does not contain specified product'));
     }
     $backupPosition = $productPositions[$productID];
     unset($productPositions[$productID]);
     $category->setPostedProducts($productPositions);
     try {
         $category->save();
     } catch (\Exception $e) {
         throw new CouldNotSaveException(__('Could not save product "%product" with position %position to category %category', ["product" => $product->getId(), "position" => $backupPosition, "category" => $category->getId()]), $e);
     }
     return true;
 }
Example #24
0
 /**
  * @magentoDataFixture Magento/Catalog/_files/categories.php
  * @magentoDbIsolation enabled
  * @magentoAppIsolation enabled
  */
 public function testInitProduct()
 {
     /** @var $objectManager \Magento\TestFramework\ObjectManager */
     $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
     $objectManager->get('Magento\\Catalog\\Model\\Session')->setLastVisitedCategoryId(2);
     $product = $this->productRepository->get('simple');
     $this->helper->initProduct($product->getId(), 'view');
     $this->assertInstanceOf('Magento\\Catalog\\Model\\Product', $objectManager->get('Magento\\Framework\\Registry')->registry('current_product'));
     $this->assertInstanceOf('Magento\\Catalog\\Model\\Category', $objectManager->get('Magento\\Framework\\Registry')->registry('current_category'));
 }
 /**
  * Assign product to given categories
  *
  * @param string $productSku
  * @param \int[] $categoryIds
  * @return bool
  */
 public function assignProductToCategories($productSku, array $categoryIds)
 {
     $product = $this->productRepository->get($productSku);
     $assignedCategories = $this->productResource->getCategoryIds($product);
     foreach (array_diff($assignedCategories, $categoryIds) as $categoryId) {
         $this->categoryLinkRepository->deleteByIds($categoryId, $productSku);
     }
     foreach (array_diff($categoryIds, $assignedCategories) as $categoryId) {
         /** @var \Magento\Catalog\Api\Data\CategoryProductLinkInterface $categoryProductLink */
         $categoryProductLink = $this->productLinkFactory->create();
         $categoryProductLink->setSku($productSku);
         $categoryProductLink->setCategoryId($categoryId);
         $categoryProductLink->setPosition(0);
         $this->categoryLinkRepository->save($categoryProductLink);
     }
     $productCategoryIndexer = $this->indexerRegistry->get(Indexer\Product\Category::INDEXER_ID);
     if (!$productCategoryIndexer->isScheduled()) {
         $productCategoryIndexer->reindexRow($product->getId());
     }
     return true;
 }
Example #26
0
 /**
  * @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
  * @magentoAppArea adminhtml
  */
 public function testConfigureProductToAddAction()
 {
     $product = $this->productRepository->get('configurable');
     $this->getRequest()->setParam('id', $product->getEntityId())->setParam('isAjax', true);
     $this->dispatch('backend/sales/order_create/configureProductToAdd');
     $body = $this->getResponse()->getBody();
     $this->assertNotEmpty($body);
     $this->assertContains('><span>Quantity</span></label>', $body);
     $this->assertContains('>Test Configurable</label>', $body);
     $this->assertContains('"code":"test_configurable","label":"Test Configurable"', $body);
     $this->assertContains(sprintf('"productId":"%s"', $product->getEntityId()), $body);
 }
Example #27
0
 /**
  * {@inheritdoc}
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function save(\Magento\Quote\Api\Data\CartItemInterface $cartItem)
 {
     $qty = $cartItem->getQty();
     if (!is_numeric($qty) || $qty <= 0) {
         throw InputException::invalidFieldValue('qty', $qty);
     }
     $cartId = $cartItem->getQuoteId();
     /** @var \Magento\Quote\Model\Quote $quote */
     $quote = $this->quoteRepository->getActive($cartId);
     $itemId = $cartItem->getItemId();
     try {
         /** update item */
         if (isset($itemId)) {
             $item = $quote->getItemById($itemId);
             if (!$item) {
                 throw new NoSuchEntityException(__('Cart %1 doesn\'t contain item  %2', $cartId, $itemId));
             }
             $productType = $item->getProduct()->getTypeId();
             $buyRequestData = $this->getBuyRequest($productType, $cartItem);
             if (is_object($buyRequestData)) {
                 /** update item product options */
                 /** @var  \Magento\Quote\Model\Quote\Item $cartItem */
                 $cartItem = $quote->updateItem($itemId, $buyRequestData);
             } else {
                 /** update item qty */
                 $item->setData('qty', $qty);
             }
         } else {
             /** add item to shopping cart */
             $product = $this->productRepository->get($cartItem->getSku());
             $productType = $product->getTypeId();
             /** @var  \Magento\Quote\Model\Quote\Item|string $cartItem */
             $cartItem = $quote->addProduct($product, $this->getBuyRequest($productType, $cartItem));
             if (is_string($cartItem)) {
                 throw new \Magento\Framework\Exception\LocalizedException(__($cartItem));
             }
         }
         $this->quoteRepository->save($quote->collectTotals());
     } catch (\Exception $e) {
         if ($e instanceof NoSuchEntityException || $e instanceof LocalizedException) {
             throw $e;
         }
         throw new CouldNotSaveException(__('Could not save quote'));
     }
     $itemId = $cartItem->getId();
     foreach ($quote->getAllItems() as $quoteItem) {
         if ($itemId == $quoteItem->getId()) {
             $cartItem = $this->addProductOptions($productType, $quoteItem);
             return $this->applyCustomOptions($cartItem);
         }
     }
     throw new CouldNotSaveException(__('Could not save quote'));
 }
 public function testGetAvailableInCategories()
 {
     $this->assertEquals([], $this->_model->getAvailableInCategories());
     $this->_model->load($this->productRepository->get('simple-4')->getId());
     // fixture
     $actualCategoryIds = $this->_model->getAvailableInCategories();
     sort($actualCategoryIds);
     // not depend on the order of items
     $this->assertEquals([10, 11, 12, 13], $actualCategoryIds);
     //Check not visible product
     $this->_model->load($this->productRepository->get('simple-3')->getId());
     $this->assertEmpty($this->_model->getAvailableInCategories());
 }
Example #29
0
 /**
  * @magentoDataFixture Magento/Customer/_files/customer.php
  * @magentoDataFixture Magento/Customer/_files/customer_address.php
  * @magentoDataFixture Magento/Tax/_files/tax_classes.php
  * @magentoDataFixture Magento/Customer/_files/customer_group.php
  * @magentoDataFixture Magento/Bundle/_files/product.php
  * @magentoConfigFixture current_store tax/calculation/algorithm UNIT_BASE_CALCULATION
  * @dataProvider collectUnitBasedDataProvider
  */
 public function testCollectUnitBasedBundleProduct($expected)
 {
     $customerTaxClassId = $this->getCustomerTaxClassId();
     $fixtureCustomerId = 1;
     /** @var \Magento\Customer\Model\Customer $customer */
     $customer = $this->objectManager->create('Magento\\Customer\\Model\\Customer')->load($fixtureCustomerId);
     /** @var \Magento\Customer\Model\Group $customerGroup */
     $customerGroup = $this->objectManager->create('Magento\\Customer\\Model\\Group')->load('custom_group', 'customer_group_code');
     $customerGroup->setTaxClassId($customerTaxClassId)->save();
     $customer->setGroupId($customerGroup->getId())->save();
     $productTaxClassId = $this->getProductTaxClassId();
     /** @var \Magento\Catalog\Model\Product $product */
     $childProduct = $this->productRepository->get('simple');
     $childProduct->setTaxClassId($productTaxClassId)->save();
     /** @var \Magento\Catalog\Model\Product $product */
     $product = $this->productRepository->get('bundle-product');
     $product->setTaxClassId($productTaxClassId)->setPriceType(\Magento\Catalog\Model\Product\Type\AbstractType::CALCULATE_CHILD)->save();
     $quoteShippingAddressDataObject = $this->getShippingAddressDataObject($fixtureCustomerId);
     /** @var \Magento\Quote\Model\Quote\Address $quoteShippingAddress */
     $quoteShippingAddress = $this->objectManager->create('Magento\\Quote\\Model\\Quote\\Address');
     $quoteShippingAddress->importCustomerAddressData($quoteShippingAddressDataObject);
     $quantity = 2;
     /** @var \Magento\Quote\Model\Quote $quote */
     $quote = $this->objectManager->create('Magento\\Quote\\Model\\Quote');
     $quote->setStoreId(1)->setIsActive(true)->setIsMultiShipping(false)->assignCustomerWithAddressChange($this->getCustomerById($customer->getId()))->setShippingAddress($quoteShippingAddress)->setBillingAddress($quoteShippingAddress)->setCheckoutMethod($customer->getMode())->setPasswordHash($customer->encryptPassword($customer->getPassword()))->addProduct($product->load($product->getId()), $quantity);
     $address = $quote->getShippingAddress();
     /** @var \Magento\Quote\Model\ShippingAssignment $shippingAssignment */
     $shippingAssignment = $this->objectManager->create('Magento\\Quote\\Model\\ShippingAssignment');
     $shipping = $this->objectManager->create('Magento\\Quote\\Model\\Shipping');
     $shipping->setAddress($address);
     $shippingAssignment->setShipping($shipping);
     $shippingAssignment->setItems($quote->getAllItems());
     /** @var  \Magento\Quote\Model\Quote\Address\Total $total */
     $total = $this->objectManager->create('Magento\\Quote\\Model\\Quote\\Address\\Total');
     /** @var \Magento\Quote\Model\Quote\Address\Total\Subtotal $addressSubtotalCollector */
     $addressSubtotalCollector = $this->objectManager->create('Magento\\Quote\\Model\\Quote\\Address\\Total\\Subtotal');
     $addressSubtotalCollector->collect($quote, $shippingAssignment, $total);
     /** @var \Magento\Tax\Model\Sales\Total\Quote\Subtotal $subtotalCollector */
     $subtotalCollector = $this->objectManager->create('Magento\\Tax\\Model\\Sales\\Total\\Quote\\Subtotal');
     $subtotalCollector->collect($quote, $shippingAssignment, $total);
     $this->assertEquals($expected['subtotal'], $total->getSubtotal());
     $this->assertEquals($expected['subtotal'] + $expected['tax_amount'], $total->getSubtotalInclTax());
     $this->assertEquals($expected['discount_amount'], $total->getDiscountAmount());
     $items = $address->getAllItems();
     /** @var \Magento\Quote\Model\Quote\Address\Item $item */
     $item = $items[0];
     $this->assertEquals($expected['items'][0]['price'], $item->getPrice());
     $this->assertEquals($expected['items'][0]['price_incl_tax'], $item->getPriceInclTax());
     $this->assertEquals($expected['items'][0]['row_total'], $item->getRowTotal());
     $this->assertEquals($expected['items'][0]['row_total_incl_tax'], $item->getRowTotalInclTax());
 }
Example #30
0
 /**
  * Update downloadable sample of the given product
  *
  * @param string $sku
  * @param \Magento\Downloadable\Api\Data\SampleInterface $sample
  * @param bool $isGlobalScopeContent
  * @return int
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function save($sku, SampleInterface $sample, $isGlobalScopeContent = false)
 {
     $product = $this->productRepository->get($sku, true);
     $sampleId = $sample->getId();
     if ($sampleId) {
         return $this->updateSample($product, $sample, $isGlobalScopeContent);
     } else {
         if ($product->getTypeId() !== \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) {
             throw new InputException(__('Product type of the product must be \'downloadable\'.'));
         }
         if (!$this->contentValidator->isValid($sample)) {
             throw new InputException(__('Provided sample information is invalid.'));
         }
         if (!in_array($sample->getSampleType(), ['url', 'file'])) {
             throw new InputException(__('Invalid sample type.'));
         }
         $title = $sample->getTitle();
         if (empty($title)) {
             throw new InputException(__('Sample title cannot be empty.'));
         }
         return $this->saveSample($product, $sample, $isGlobalScopeContent);
     }
 }