![]() Server : Apache System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64 User : corals ( 1002) PHP Version : 7.4.33 Disable Function : exec,passthru,shell_exec,system Directory : /home/corals/cartforge.co/app/code/CartForge/Utility/Controller/Adminhtml/Label/ |
<?php namespace CartForge\Utility\Controller\Adminhtml\Label; use Amasty\Label\Api\LabelRepositoryInterface; use Amasty\Label\Api\Data\LabelInterface; use Amasty\Label\Model\Label\Save\Adminhtml\SaveFromEditForm; use Amasty\Label\Model\LabelRegistry; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Psr\Log\LoggerInterface; use Throwable; class Save extends Action { public const ADMIN_RESOURCE = 'Amasty_Label::label_save'; private $labelRepository; private $labelRegistry; private $saveFromEditForm; private $logger; private $resourceConnection; public function __construct( Context $context, LabelRepositoryInterface $labelRepository, SaveFromEditForm $saveFromEditForm, LabelRegistry $labelRegistry, LoggerInterface $logger, ResourceConnection $resourceConnection ) { $this->labelRepository = $labelRepository; $this->labelRegistry = $labelRegistry; $this->saveFromEditForm = $saveFromEditForm; $this->logger = $logger; $this->resourceConnection = $resourceConnection; parent::__construct($context); } public function execute() { $postData = $this->getRequest()->getPostValue(); $currentLabel = $this->getCurrentLabel(); $this->labelRegistry->setCurrentLabel($currentLabel); $resultRedirect = $this->resultRedirectFactory->create(); try { $postData[LabelInterface::LABEL_ID] = $currentLabel->getId() === null ? null : $currentLabel->getLabelId(); // Get current product IDs associated with the label $currentProductIds = $this->getProductIdsByLabel($currentLabel->getLabelId()); // Save the label with updated data $currentLabel = $this->saveFromEditForm->execute($postData); $this->_getSession()->unsAmLabelPageData($postData); // Get new product IDs after save $newProductIds = $this->getProductIdsByLabel($currentLabel->getLabelId()); // Update product positions $this->updateProductPositions($currentLabel, $currentProductIds, $newProductIds); $this->messageManager->addSuccessMessage(__('You saved the label')); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); $this->_getSession()->setAmLabelPageData($postData); } catch (Throwable $e) { $this->messageManager->addErrorMessage( __('Something went wrong while saving the item data. Please review the error log.') ); $this->logger->critical($e); $this->_getSession()->setAmLabelPageData($postData); } $needGoBack = (bool)$this->getRequest()->getParam('back', false); $labelId = $currentLabel->getLabelId(); $redirectParams = $needGoBack ? ['amasty_label/*/edit', ['id' => $labelId]] : ['amasty_label/label/index']; return $resultRedirect->setPath(...$redirectParams); } private function getCurrentLabel(): LabelInterface { $labelId = (int)$this->getRequest()->getParam(LabelInterface::LABEL_ID); try { $currentLabel = $this->labelRepository->getById($labelId); } catch (NoSuchEntityException $e) { $currentLabel = $this->labelRepository->getModelLabel(); } return $currentLabel; } private function getProductIdsByLabel(int $labelId): array { $connection = $this->resourceConnection->getConnection(); $productsTable = $connection->getTableName('amasty_label_index'); // Adjust table name return $connection->fetchCol( $connection->select() ->from($productsTable, ['product_id']) ->where('label_id = ?', $labelId) ); } private function updateProductPositions(LabelInterface $label, array $currentProductIds, array $newProductIds) { $connection = $this->resourceConnection->getConnection(); try { // Determine removed products $removedProductIds = array_diff($currentProductIds, $newProductIds); // Determine newly added products $newlyAddedProductIds = array_diff($newProductIds, $currentProductIds); // Handle removed products if (!empty($removedProductIds)) { $this->logger->info("Products removed for label ID {$label->getLabelId()}: " . implode(', ', $removedProductIds)); // Get all product IDs associated with labels other than the current one $productsTable = $connection->getTableName('amasty_label_index'); $productsWithOtherLabels = $connection->fetchCol( $connection->select() ->distinct() ->from($productsTable, ['product_id']) ->where('label_id != ?', $label->getLabelId()) ); $this->logger->info("Products with other labels (excluding current label): " . implode(', ', $productsWithOtherLabels)); // Compare removed products with products associated with other labels $productsToResetPosition = array_diff($removedProductIds, $productsWithOtherLabels); if (!empty($productsToResetPosition)) { $this->logger->info("Products to reset position: " . implode(', ', $productsToResetPosition)); // Reset positions to 1 for these products $catalogTable = $connection->getTableName('catalog_category_product'); $connection->update( $catalogTable, ['position' => 1], ['product_id IN (?)' => $productsToResetPosition] ); $this->logger->info("Successfully reset positions for products: " . implode(', ', $productsToResetPosition)); } else { $this->logger->info("No products need position reset."); } } // Handle newly added products if (!empty($newlyAddedProductIds)) { $this->logger->info("Products added for label ID {$label->getLabelId()}: " . implode(', ', $newlyAddedProductIds)); $catalogTable = $connection->getTableName('catalog_category_product'); $connection->update( $catalogTable, ['position' => 0], // Set position to 0 for newly added products ['product_id IN (?)' => $newlyAddedProductIds] ); $this->logger->info("Successfully updated positions for newly added products."); } } catch (Throwable $e) { $this->logger->critical("Error updating product positions: " . $e->getMessage()); } } }