Files
2026-09-15 10:26:34 +08:00

149 lines
6.1 KiB
PHP
Executable File

<?php
/**
* Magezon
*
* This source file is subject to the Magezon Software License, which is available at https://www.magezon.com/license/.
* Do not edit or add to this file if you wish to upgrade the to newer versions in the future.
* If you wish to customize this module for your needs.
* Please refer to https://www.magezon.com for more information.
*
* @category Magezon
* @package Magezon_QuickOrder
* @copyright Copyright (C) 2018 Magezon (https://www.magezon.com)
*/
namespace Magezon\QuickOrder\Controller\Index;
use \Magento\Framework\Exception\LocalizedException;
use Psr\Log\LoggerInterface;
use Stemcell\Customer\Model\LabRepository;
class AddToCart extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Checkout\Model\Cart
*/
protected $cart;
/**
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
protected $productRepository;
protected LabRepository $labRepository;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Checkout\Model\Cart $cart
* @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
LabRepository $labRepository,
protected LoggerInterface $logger
) {
parent::__construct($context);
$this->cart = $cart;
$this->productRepository = $productRepository;
$this->labRepository = $labRepository;
}
public function execute()
{
$result['status'] = false;
$data = $this->getRequest()->getPostValue();
// $this->logger->warning('$data', $data);
$extensionAttributes = [];
$storeId = $this->_objectManager->get(\Magento\Store\Model\StoreManagerInterface::class)->getStore()->getId();
if ($data && isset($data['items'])) {
try {
$valid = true;
$shouldCollectTotals = false;
foreach ($data['items'] as $index => $item) {
if (!isset($item['product'])) {
if (isset($item['name']) && $item['name']) {
$this->messageManager->addError(__('Product %1 does not exist. Please remove and add it again.', $item['name']));
} else {
$this->messageManager->addError(__('Something went wrong while processing the request.'));
}
$valid = false;
break;
}
$product = $this->productRepository->getById($item['product'], false, $storeId, true);
$params = [];
if (isset($item['options'])) {
parse_str($item['options'], $params);
}
$extensionAttributes[$product->getId()] = $item['others'];
$params['qty'] = $item['qty'];
$params['item_sort'] = $index + 1;
try {
$this->cart->addProduct($product, $params);
} catch (\Exception $e) {
$valid = false;
$this->logger->warning('货号直购将产品加入购物车时异常,原因:'.$e->getMessage(), $e->getTrace());
$this->messageManager->addError(__('Something went wrong while processing the request.'));
}
}
$cart = $this->cart->save();
if ($valid) {
$firstLab = false;
$valid = false;
foreach ($cart->getQuote()->getAllVisibleItems() as $item) {
$productId = $item->getProduct()->getId();
if (isset($extensionAttributes[$productId]) && is_array($extensionAttributes[$productId])) {
try {
$lab = $this->labRepository->getByLabCode($extensionAttributes[$productId]['lab_code']);
if ($lab->getLabId()) {
$extensionAttributes[$productId]['lab_id'] = $lab->getLabId();
if ($lab->getSalespersonId()) {
$firstLab = $lab;
}
}
} catch (LocalizedException $e) {
$this->logger->warning(
sprintf(
'货号直购设置lab时异常,lab_code: %s, 原因:%s',
$extensionAttributes[$productId]['lab_code'],
$e->getMessage()
),
$e->getTrace()
);
}
$percent = $extensionAttributes[$productId]['customer_discount_percent'] ?? 0;
if (intval($percent) != 0) {
$shouldCollectTotals = true;
}
$cart->updateItems([$item->getId()=>['extension_attributes'=>$extensionAttributes[$item->getProduct()->getId()]]]);
$valid = true;
}
}
if ($firstLab) {
$cart->getQuote()->setData('salesperson_id', $firstLab->getSalespersonId());
}
// if ($valid) {
// $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' => $cart]);
// $this->cart->save();
// }
if ($shouldCollectTotals) {
$this->cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
}
$result['status'] = true;
$result['redirectUrl'] = $this->_url->getUrl('checkout/cart');
}
} catch (LocalizedException $e) {
$result['message'] = $e->getMessage();
} catch (\Exception $e) {
$result['message'] = __('Something went wrong while processing the request.');
}
}
$this->getResponse()->representJson(
$this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($result)
);
return;
}
}