This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Stemcell\Checkout\Api;
use Stemcell\Checkout\Api\Data\Quote\TotalsInterface;
/**
* Interface CartTotalRepositoryInterface
* @api
* @since 100.0.2
*/
interface CartTotalRepositoryInterface
{
/**
* Returns quote totals data for a specified cart.
*
* @param int $cartId The cart ID.
* @return TotalsInterface Quote totals data.
* @throws \Magento\Framework\Exception\NoSuchEntityException The specified cart does not exist.
*/
public function get($cartId);
}
@@ -0,0 +1,22 @@
<?php
namespace Stemcell\Checkout\Api\Data\Quote;
interface TotalsInterface extends \Magento\Quote\Api\Data\TotalsInterface
{
/**
* Get totals by items
*
* @return \Stemcell\Checkout\Api\Data\Quote\TotalsItemInterface[]|null
*/
public function getItems();
/**
* Set totals by items
*
* @param \Stemcell\Checkout\Api\Data\Quote\TotalsItemInterface[] $items
* @return $this
*/
public function setItems(array $items = null);
}
@@ -0,0 +1,111 @@
<?php
namespace Stemcell\Checkout\Api\Data\Quote;
interface TotalsItemInterface extends \Magento\Quote\Api\Data\TotalsItemInterface
{
const SKU = 'sku';
const SALESPERSON_NAME = 'salesperson_name';
const LAB_BOOKING_ACCOUNT = 'lab_booking_account';
const CD_CODE = 'cd_code';
const QUOTE_CODE = 'quote_code';
const PI_SAP_ID = 'pi_sap_id';
const CUSTOMER_DISCOUNT_PERCENT = 'customer_discount_percent';
const NOTE = 'note';
/**
* @return string
*/
public function getSku();
/**
* @param string $sku
* @return self
*/
public function setSku(string $sku);
/**
* @return string
*/
public function getSalespersonName();
/**
* @param string | null $salespersonName
* @return self
*/
public function setSalespersonName(string | null $salespersonName);
/**
* @return string
*/
public function getLabBookingAccount();
/**
* @param string $labBookingAccount
* @return self
*/
public function setLabBookingAccount(string $labBookingAccount);
/**
* @return string
*/
public function getCdCode();
/**
* @param string $cdCode
* @return self
*/
public function setCdCode(string $cdCode);
/**
* @return string
*/
public function getQuoteCode();
/**
* @param string $quoteCode
* @return self
*/
public function setQuoteCode(string $quoteCode);
/**
* @return string
*/
public function getPiSapId();
/**
* @param string $piSapId
* @return self
*/
public function setPiSapId(string $piSapId);
/**
* @return string
*/
public function getCustomerDiscountPercent();
/**
* @param string $customerDiscountPercent
* @return self
*/
public function setCustomerDiscountPercent(string $customerDiscountPercent);
/**
* @return string
*/
public function getNote();
/**
* @param string $note
* @return self
*/
public function setNote(string $note);
}
@@ -0,0 +1,66 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Stemcell\Checkout\Block\Cart;
use Magento\Customer\Model\Session;
use Magento\Framework\Data\CollectionFactory;
use Stemcell\Customer\Model\ResourceModel;
use Stemcell\Customer\Model\Salesperson;
class Grid extends \Magento\Checkout\Block\Cart\Grid
{
protected ResourceModel\Salesperson\Collection $salespersonCollection;
protected CollectionFactory $baseCollectionFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Catalog\Model\ResourceModel\Url $catalogUrlBuilder,
\Magento\Checkout\Helper\Cart $cartHelper,
\Magento\Framework\App\Http\Context $httpContext,
\Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory $itemCollectionFactory,
\Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface $joinProcessor,
ResourceModel\Salesperson\Collection $salespersonCollection,
CollectionFactory $baseCollectionFactory,
array $data = []
) {
parent::__construct(
$context,
$customerSession,
$checkoutSession,
$catalogUrlBuilder,
$cartHelper,
$httpContext,
$itemCollectionFactory,
$joinProcessor,
$data
);
$this->baseCollectionFactory = $baseCollectionFactory;
$this->salespersonCollection = $salespersonCollection;
}
public function getSalesperson(): \Magento\Framework\Data\Collection|ResourceModel\Salesperson\Collection
{
if ($this->_customerSession->getCustomerId()) {
$this->salespersonCollection->getSelect()->joinInner(
'customer_salesperson',
'customer_salesperson.salesperson_id = main_table.salesperson_id and
customer_salesperson.customer_id = '.$this->_customerSession->getCustomerId(),
);
return $this->salespersonCollection;
}
return $this->baseCollectionFactory->create()->setItemObjectClass(Salesperson::class);
}
public function getQuoteData($key) {
return $this->getQuote()? $this->getQuote()->getData($key):null;
}
}
@@ -0,0 +1,85 @@
<?php
namespace Stemcell\Checkout\Block\Cart\Item\Bundle;
use Magento\Bundle\Helper\Catalog\Product\Configuration;
use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface;
use Magento\Customer\Model\Session;
use Magento\Framework\Data\CollectionFactory;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\View\Element\Message\InterpretationStrategyInterface;
use Stemcell\Customer\Model\ResourceModel;
class Renderer extends \Stemcell\Checkout\Block\Cart\Item\Renderer
{
/**
* Bundle catalog product configuration
*
* @var Configuration
*/
protected Configuration $_bundleProductConfiguration;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Helper\Product\Configuration $productConfig,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Catalog\Block\Product\ImageBuilder $imageBuilder,
\Magento\Framework\Url\Helper\Data $urlHelper,
\Magento\Framework\Message\ManagerInterface $messageManager,
PriceCurrencyInterface $priceCurrency,
\Magento\Framework\Module\Manager $moduleManager,
InterpretationStrategyInterface $messageInterpretationStrategy,
ResourceModel\Lab\Collection $labCollection,
ResourceModel\Salesperson\Collection $salespersonCollection,
CollectionFactory $baseCollectionFactory,
Session $customerSession,
Configuration $bundleProductConfiguration,
array $data = [],
ItemResolverInterface $itemResolver = null
) {
$this->_bundleProductConfiguration = $bundleProductConfiguration;
parent::__construct(
$context,
$productConfig,
$checkoutSession,
$imageBuilder,
$urlHelper,
$messageManager,
$priceCurrency,
$moduleManager,
$messageInterpretationStrategy,
$labCollection,
$salespersonCollection,
$baseCollectionFactory,
$customerSession,
$data,
$itemResolver
);
}
public function getOptionList()
{
return $this->_bundleProductConfiguration->getOptions($this->getItem());
}
/**
* Return cart item error messages
*
* @return array
*/
public function getMessages()
{
$messages = [];
$quoteItem = $this->getItem();
// Add basic messages occurring during this page load
$baseMessages = $quoteItem->getMessage(false);
if ($baseMessages) {
foreach ($baseMessages as $message) {
$messages[] = ['text' => $message, 'type' => $quoteItem->getHasError() ? 'error' : 'notice'];
}
}
return $messages;
}
}
@@ -0,0 +1,125 @@
<?php
namespace Stemcell\Checkout\Block\Cart\Item;
use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface;
use Magento\Customer\Model\Session;
use Magento\Framework\Data\Collection;
use Magento\Framework\Data\CollectionFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\View\Element\Message\InterpretationStrategyInterface;
use Stemcell\Customer\Model\Lab;
use Stemcell\Customer\Model\LabFactory;
use Stemcell\Customer\Model\LabRepository;
use Stemcell\Customer\Model\Salesperson;
use Stemcell\Customer\Model\ResourceModel;
use Stemcell\Customer\Model\SalespersonRepository;
class Renderer extends \Magento\Checkout\Block\Cart\Item\Renderer
{
protected ResourceModel\Lab\Collection $labCollection;
protected ResourceModel\Salesperson\Collection $salespersonCollection;
protected Session $customerSession;
protected CollectionFactory $baseCollectionFactory;
protected ?Lab $lab = null;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Catalog\Helper\Product\Configuration $productConfig
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Catalog\Block\Product\ImageBuilder $imageBuilder
* @param \Magento\Framework\Url\Helper\Data $urlHelper
* @param \Magento\Framework\Message\ManagerInterface $messageManager
* @param PriceCurrencyInterface $priceCurrency
* @param \Magento\Framework\Module\Manager $moduleManager
* @param InterpretationStrategyInterface $messageInterpretationStrategy
* @param ResourceModel\Lab\Collection $labCollection
* @param ResourceModel\Salesperson\Collection $salespersonCollection
* @param array $data
* @param ItemResolverInterface|null $itemResolver
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Helper\Product\Configuration $productConfig,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Catalog\Block\Product\ImageBuilder $imageBuilder,
\Magento\Framework\Url\Helper\Data $urlHelper,
\Magento\Framework\Message\ManagerInterface $messageManager,
PriceCurrencyInterface $priceCurrency,
\Magento\Framework\Module\Manager $moduleManager,
InterpretationStrategyInterface $messageInterpretationStrategy,
ResourceModel\Lab\Collection $labCollection,
ResourceModel\Salesperson\Collection $salespersonCollection,
CollectionFactory $baseCollectionFactory,
Session $customerSession,
array $data = [],
ItemResolverInterface $itemResolver = null
)
{
parent::__construct(
$context,
$productConfig,
$checkoutSession,
$imageBuilder,
$urlHelper,
$messageManager,
$priceCurrency,
$moduleManager,
$messageInterpretationStrategy,
$data,
$itemResolver
);
$this->customerSession = $customerSession;
$this->baseCollectionFactory = $baseCollectionFactory;
$this->labCollection = $labCollection;
$this->salespersonCollection = $salespersonCollection;
}
public function getLabs(): Collection|ResourceModel\Lab\Collection
{
if ($this->customerSession->getCustomerId()) {
$this->labCollection->addFieldToFilter('main_table.customer_id', $this->customerSession->getCustomerId())
->getSelect()
->joinLeft('salesperson', 'salesperson.salesperson_id=main_table.salesperson_id', ['salesperson'=>'salesperson.name']);
return $this->labCollection;
}
return $this->baseCollectionFactory->create()->setItemObjectClass(Lab::class);
}
/**
* @return \Stemcell\Customer\Api\Data\LabInterface|Lab
*/
public function getLab()
{
try {
if ($labId = $this->_item->getData('lab_id')) {
/* @var $labRepository LabRepository */
$labRepository = \Magento\Framework\App\ObjectManager::getInstance()->get(LabRepository::class);
/* @var $salespersonRepository SalespersonRepository */
$salespersonRepository = \Magento\Framework\App\ObjectManager::getInstance()->get(SalespersonRepository::class);
$this->lab = $labRepository->get($labId);
$salesperson = $salespersonRepository->get($this->lab->getSalespersonId());
$this->lab->setData('salesperson', $salesperson->getName());
return $this->lab;
}
} catch (LocalizedException $e) {
}
/* @var $labFactory LabFactory */
$labFactory = \Magento\Framework\App\ObjectManager::getInstance()->get(LabFactory::class);
return $labFactory->create();
}
public function getSalesperson() {
if ($this->customerSession->getCustomerId()) {
$this->salespersonCollection->addFieldToFilter('customer_id', $this->customerSession->getCustomerId());
return $this->salespersonCollection;
}
return $this->baseCollectionFactory->create()->setItemObjectClass(Salesperson::class);
}
}
@@ -0,0 +1,80 @@
<?php
namespace Stemcell\Checkout\Block\Cart\Item\Renderer;
use Stemcell\Checkout\Block\Cart\Item\Renderer;
use Magento\Framework\DataObject\IdentityInterface;
class Configurable extends Renderer implements IdentityInterface
{
/**
* Path in config to the setting which defines if parent or child product should be used to generate a thumbnail.
* @deprecated moved to model because of class refactoring
* @see \Magento\ConfigurableProduct\Model\Product\Configuration\Item\ItemProductResolver::CONFIG_THUMBNAIL_SOURCE
*/
const CONFIG_THUMBNAIL_SOURCE = 'checkout/cart/configurable_product_image';
/**
* Get item configurable child product
*
* @return \Magento\Catalog\Model\Product|null
*/
public function getChildProduct()
{
if ($option = $this->getItem()->getOptionByCode('simple_product')) {
return $option->getProduct();
}
return $this->getProduct();
}
/**
* Get item product name
*
* @return string
*/
public function getProductName()
{
if ($option = $this->getItem()->getOptionByCode('simple_product')) {
return $option->getProduct()->getName();
}
return $this->getProduct()->getName();
}
/**
* Get list of all options for product
*
* @return array
*/
public function getOptionList()
{
return $this->_productConfig->getOptions($this->getItem());
}
/**
* Return identifiers for produced content
*
* @return array
*/
public function getIdentities()
{
$identities = parent::getIdentities();
if ($this->getItem()) {
$identities = array_merge($identities, $this->getChildProduct()->getIdentities());
}
return $identities;
}
/**
* Get price for exact simple product added to cart
*
* @inheritdoc
* @since 100.3.1
*/
public function getProductPriceHtml(\Magento\Catalog\Model\Product $product)
{
return parent::getProductPriceHtml($this->getChildProduct());
}
}
{
}
@@ -0,0 +1,55 @@
<?php
namespace Stemcell\Checkout\Block\Catalog\Product;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Helper\Product as ProductHelper;
use Magento\Catalog\Model\ProductTypes\ConfigInterface;
use Magento\Customer\Model\Session;
use Magento\Framework\Locale\FormatInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\Stdlib\StringUtils;
use Magento\Framework\Url\EncoderInterface;
use Magento\Framework\Json\EncoderInterface as JsonEncoderInterface;
use \Magento\Catalog\Block\Product\Context;
class View extends \Magento\Catalog\Block\Product\View
{
public function __construct(
Context $context,
EncoderInterface $urlEncoder,
JsonEncoderInterface $jsonEncoder,
StringUtils $string,
ProductHelper $productHelper,
ConfigInterface $productTypeConfig,
FormatInterface $localeFormat,
Session $customerSession, ProductRepositoryInterface $productRepository,
PriceCurrencyInterface $priceCurrency,
array $data = []
) {
parent::__construct(
$context,
$urlEncoder,
$jsonEncoder,
$string,
$productHelper,
$productTypeConfig,
$localeFormat,
$customerSession,
$productRepository,
$priceCurrency,
$data
);
}
public function getBundleProductOptions(\Magento\Catalog\Model\Product $product)
{
//get all the selection products used in bundle product.
return $product->getTypeInstance()
->getSelectionsCollection(
$product->getTypeInstance()->getOptionsIds($product),
$product
);
}
}
@@ -0,0 +1,40 @@
<?php
namespace Stemcell\Checkout\Controller\Cart;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\ObjectManager;
use Psr\Log\LoggerInterface;
use Stemcell\Customer\Model\ResourceModel\Lab\CollectionFactory as LabCollectionFactory;
use Stemcell\Customer\Model\ResourceModel\Salesperson\CollectionFactory as SalespersonCollectionFactory;
/**
* 找到与销售、当前登录的经销商绑定的Lab
*/
class GetLabsFromSalesperson implements HttpGetActionInterface
{
public function __construct(
protected Context $context,
protected \Magento\Customer\Model\Session $customerSession,
protected \Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
protected LabCollectionFactory $labCollectionFactory,
protected SalespersonCollectionFactory $salespersonCollectionFactory
){
}
public function execute() {
$data = [];
if ($this->customerSession->isLoggedIn()) {
$salespersonId = $this->context->getRequest()->getParam('salesperson_id', 0);
$data = $this->labCollectionFactory->create()
->addFieldToFilter('is_active', 1)
->addFieldToFilter('salesperson_id', $salespersonId)
->addFieldToFilter('customer_id', $this->customerSession->getCustomerId())
->addFieldToSelect(['lab_id', 'lab_code', 'booking_account'])
->getData();
}
return $this->jsonFactory->create()->setData(['labs' => $data]);
}
}
@@ -0,0 +1,129 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Stemcell\Checkout\Controller\Cart;
use Magento\Checkout\Model\Cart\RequestQuantityProcessor;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Action\HttpGetActionInterface;
/**
* Post update shopping cart.
*/
class UpdatePost extends \Magento\Checkout\Controller\Cart implements HttpGetActionInterface, HttpPostActionInterface
{
/**
* @var RequestQuantityProcessor
*/
private $quantityProcessor;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
* @param \Magento\Checkout\Model\Cart $cart
* @param RequestQuantityProcessor $quantityProcessor
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
\Stemcell\Checkout\Model\Cart $cart,
RequestQuantityProcessor $quantityProcessor = null
) {
parent::__construct(
$context,
$scopeConfig,
$checkoutSession,
$storeManager,
$formKeyValidator,
$cart
);
$this->quantityProcessor = $quantityProcessor ?: $this->_objectManager->get(RequestQuantityProcessor::class);
}
/**
* Empty customer's shopping cart
*
* @return void
*/
protected function _emptyShoppingCart()
{
try {
$this->cart->truncate()->save();
} catch (\Magento\Framework\Exception\LocalizedException $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
} catch (\Exception $exception) {
$this->messageManager->addExceptionMessage($exception, __('We can\'t update the shopping cart.'));
}
}
/**
* Update customer's shopping cart
*
* @return void
*/
protected function _updateShoppingCart()
{
try {
$cartData = $this->getRequest()->getParam('cart');
if (is_array($cartData)) {
if (!$this->cart->getCustomerSession()->getCustomerId() && $this->cart->getQuote()->getCustomerId()) {
$this->cart->getQuote()->setCustomerId(null);
}
$cartData = $this->quantityProcessor->process($cartData);
$cartData = $this->cart->suggestItemsQty($cartData);
$this->cart->updateItems($cartData)->save();
$this->cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
}
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addErrorMessage(
$this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($e->getMessage())
);
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, __('We can\'t update the shopping cart.'));
$this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
}
}
/**
* Update shopping cart data action
*
* @return \Magento\Framework\Controller\Result\Redirect
*/
public function execute()
{
if (!$this->_formKeyValidator->validate($this->getRequest())) {
return $this->resultRedirectFactory->create()->setPath('*/*/');
}
$updateAction = (string)$this->getRequest()->getParam('update_cart_action');
switch ($updateAction) {
case 'empty_cart':
$this->_emptyShoppingCart();
break;
case 'update_qty':
$this->_updateShoppingCart();
break;
default:
$this->_updateShoppingCart();
}
if ($this->getRequest()->getParam('goCheckout')==1) {
return $this->resultRedirectFactory->create()->setPath('checkout');
}
return $this->_goBack();
}
}
@@ -0,0 +1,101 @@
<?php
namespace Stemcell\Checkout\Helper\Catalog\Product;
use Magento\Catalog\Model\Product\Configuration\Item\ItemInterface;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Escaper;
use Magento\Framework\Pricing\Helper\Data;
use Magento\Framework\Serialize\Serializer\Json;
class Configuration extends \Magento\Bundle\Helper\Catalog\Product\Configuration
{
/**
* Serializer interface instance.
*
* @var Json
*/
protected Json $serializer;
public function __construct(
Context $context,
\Magento\Catalog\Helper\Product\Configuration $productConfiguration,
Data $pricingHelper,
Escaper $escaper,
Json $serializer = null
) {
parent::__construct($context, $productConfiguration, $pricingHelper, $escaper, $serializer);
$this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Framework\Serialize\Serializer\Json::class);
}
/**
* Get bundled selections (slections-products collection)
*
* Returns array of options objects.
* Each option object will contain array of selections objects
*
* @param ItemInterface $item
* @return array
*/
public function getBundleOptions(ItemInterface $item): array
{
$options = [];
$product = $item->getProduct();
/** @var \Magento\Bundle\Model\Product\Type $typeInstance */
$typeInstance = $product->getTypeInstance();
// get bundle options
$optionsQuoteItemOption = $item->getOptionByCode('bundle_option_ids');
$bundleOptionsIds = $optionsQuoteItemOption
? $this->serializer->unserialize($optionsQuoteItemOption->getValue())
: [];
if ($bundleOptionsIds) {
/** @var \Magento\Bundle\Model\ResourceModel\Option\Collection $optionsCollection */
$optionsCollection = $typeInstance->getOptionsByIds($bundleOptionsIds, $product);
// get and add bundle selections collection
$selectionsQuoteItemOption = $item->getOptionByCode('bundle_selection_ids');
$bundleSelectionIds = $this->serializer->unserialize($selectionsQuoteItemOption->getValue());
if (!empty($bundleSelectionIds)) {
$selectionsCollection = $typeInstance->getSelectionsByIds($bundleSelectionIds, $product);
$bundleOptions = $optionsCollection->appendSelections($selectionsCollection, true);
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$option = ['label' => $bundleOption->getTitle(), 'value' => []];
$bundleSelections = $bundleOption->getSelections();
foreach ($bundleSelections as $bundleSelection) {
/* @var $bundleSelection \Magento\Catalog\Model\Product */
$qty = $this->getSelectionQty($product, $bundleSelection->getSelectionId()) * 1;
if ($qty) {
$option['value'][] = '<div class="bundle-option"><div class="bundle-option-name">'.
$this->escaper->escapeHtml($bundleSelection->getName())
.'</div>'
.'<div class="bundle-option-sku">'
.'<span class="bundle-option-label">SKU:</span>'.$bundleSelection->getSku()
.'</div>'
. '<div class="bundle-option-qty">'
. '<span class="bundle-option-lable">数量:</span>'.$qty.''
.'</div></div>';
$option['has_html'] = true;
}
}
if ($option['value']) {
$options[] = $option;
}
}
}
}
}
return $options;
}
}
+180
View File
@@ -0,0 +1,180 @@
<?php
namespace Stemcell\Checkout\Model;
use Magento\Catalog\Model\Product;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\LocalizedException;
use Psr\Log\LoggerInterface;
class Cart extends \Magento\Checkout\Model\Cart
{
/**
* Update cart items information
*
* @param array $data
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function updateItems($data)
{
$infoDataObject = new \Magento\Framework\DataObject($data);
$this->_eventManager->dispatch(
'checkout_cart_update_items_before',
['cart' => $this, 'info' => $infoDataObject]
);
$qtyRecalculatedFlag = false;
foreach ($data as $itemId => $itemInfo) {
$item = $this->getQuote()->getItemById($itemId);
if (!$item) {
continue;
}
if (!empty($itemInfo['remove']) || isset($itemInfo['qty']) && $itemInfo['qty'] == '0') {
$this->removeItem($itemId);
continue;
}
$qty = isset($itemInfo['qty']) ? (double)$itemInfo['qty'] : false;
if ($qty > 0) {
$item->clearMessage();
$item->setHasError(false);
$item->setQty($qty);
if ($item->getHasError()) {
throw new \Magento\Framework\Exception\LocalizedException(__($item->getMessage()));
}
if (isset($itemInfo['before_suggest_qty']) && $itemInfo['before_suggest_qty'] != $qty) {
$qtyRecalculatedFlag = true;
$this->messageManager->addNoticeMessage(
__('Quantity was recalculated from %1 to %2', $itemInfo['before_suggest_qty'], $qty),
'quote_item' . $item->getId()
);
}
}
if (isset($itemInfo['extension_attributes']) && is_array($itemInfo['extension_attributes'])) {
foreach ($itemInfo['extension_attributes'] as $attribute => $val) {
if ($val!='' || $val!=null) {
$item->setData($attribute, $val);
}
}
}
if (!empty($itemInfo['discount_percent'])) {
$item->setDiscountAmount($item->getRowTotal()*$itemInfo['discount_percent']);
$item->setDiscountPercent($itemInfo['discount_percent']);
}
// $item->setRowTotal($item->getRowTotal());
// $item->setDiscountPercent($itemInfo['discount_percent']);
}
isset($data['salesperson_id']) && $this->getQuote()->setData('salesperson_id', $data['salesperson_id']);
isset($data['customer_note']) && $this->getQuote()->setCustomerNote($data['customer_note']);
if ($qtyRecalculatedFlag) {
$this->messageManager->addNoticeMessage(
__('We adjusted product quantities to fit the required increments.')
);
}
$this->_eventManager->dispatch(
'checkout_cart_update_items_after',
['cart' => $this, 'info' => $infoDataObject]
);
return $this;
}
/**
* Get request quantity
*
* @param Product $product
* @param \Magento\Framework\DataObject|int|array $request
* @return int|DataObject
* @throws LocalizedException
*/
protected function getQtyRequest($product, $request = 0)
{
$request = $this->_getProductRequest($request);
$stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId());
$minimumQty = $stockItem->getMinSaleQty();
//If product quantity is not specified in request and there is set minimal qty for it
if ($minimumQty
&& $minimumQty > 0
&& !$request->getQty()
) {
$request->setQty($minimumQty);
}
return $request;
}
/**
* Add product to shopping cart (quote)
*
* @param int|Product $productInfo
* @param \Magento\Framework\DataObject|int|array $requestInfo
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function addProduct($productInfo, $requestInfo = null)
{
$product = $this->_getProduct($productInfo);
$productId = $product->getId();
if ($productId) {
$request = $this->getQtyRequest($product, $requestInfo);
try {
$this->_eventManager->dispatch(
'checkout_cart_product_add_before',
['info' => $requestInfo, 'product' => $product]
);
$result = $this->getQuote()->addProduct($product, $request);
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->_checkoutSession->setUseNotice(false);
$result = $e->getMessage();
}
/**
* String we can get if prepare process has error
*/
if (is_string($result)) {
if ($product->hasOptionsValidationFail()) {
$redirectUrl = $product->getUrlModel()->getUrl(
$product,
['_query' => ['startcustomization' => 1]]
);
} else {
$redirectUrl = $product->getProductUrl();
}
$this->_checkoutSession->setRedirectUrl($redirectUrl);
if ($this->_checkoutSession->getUseNotice() === null) {
$this->_checkoutSession->setUseNotice(true);
}
throw new \Magento\Framework\Exception\LocalizedException(__($result));
}
} else {
throw new \Magento\Framework\Exception\LocalizedException(__('The product does not exist.'));
}
$this->_eventManager->dispatch(
'checkout_cart_product_add_after',
['quote_item' => $result, 'product' => $product]
);
$this->_checkoutSession->setLastAddedProductId($productId);
return $this;
}
public function truncate()
{
$this->getQuote()->removeAllItems();
$this->getQuote()->setCustomerNote(null)->setData('salesperson_id', 0);
return $this;
}
}
@@ -0,0 +1,112 @@
<?php
namespace Stemcell\Checkout\Model\Cart;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\ExtensibleDataInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Quote\Api;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\CouponManagementInterface;
use Magento\Quote\Model\Cart\Totals\ItemConverter;
use Magento\Quote\Model\Cart\TotalsConverter;
use Psr\Log\LoggerInterface;
use Stemcell\Checkout\Api\Data\Quote\TotalsInterface;
use Stemcell\Checkout\Api\Data\Quote\TotalsInterfaceFactory;
use Stemcell\Checkout\Model\Cart\Totals\Item;
class CartTotalRepository extends \Magento\Quote\Model\Cart\CartTotalRepository
{
private TotalsInterfaceFactory $totalsInterfaceFactory;
/**
* Cart totals factory.
*
* @var Api\Data\TotalsInterfaceFactory
*/
private $totalsFactory;
/**
* @var \Magento\Quote\Api\CartRepositoryInterface
*/
private $quoteRepository;
/**
* @var \Magento\Framework\Api\DataObjectHelper
*/
private $dataObjectHelper;
/**
* @var ItemConverter
*/
private $itemConverter;
/**
* @var CouponManagementInterface
*/
protected $couponService;
/**
* @var TotalsConverter
*/
protected $totalsConverter;
public function __construct(
Api\Data\TotalsInterfaceFactory $totalsFactory,
TotalsInterfaceFactory $totalsInterfaceFactory,
CartRepositoryInterface $quoteRepository,
DataObjectHelper $dataObjectHelper,
CouponManagementInterface $couponService,
TotalsConverter $totalsConverter,
ItemConverter $converter
) {
parent::__construct($totalsFactory, $quoteRepository, $dataObjectHelper, $couponService, $totalsConverter, $converter);
$this->totalsInterfaceFactory = $totalsInterfaceFactory;
$this->totalsFactory = $totalsFactory;
$this->quoteRepository = $quoteRepository;
$this->dataObjectHelper = $dataObjectHelper;
$this->couponService = $couponService;
$this->totalsConverter = $totalsConverter;
$this->itemConverter = $converter;
}
/**
* @param $cartId
* @return TotalsInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function get($cartId): TotalsInterface
{
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $this->quoteRepository->getActive($cartId);
if ($quote->isVirtual()) {
$quote->collectTotals();
$addressTotalsData = $quote->getBillingAddress()->getData();
$addressTotals = $quote->getBillingAddress()->getTotals();
} else {
$addressTotalsData = $quote->getShippingAddress()->getData();
$addressTotals = $quote->getShippingAddress()->getTotals();
}
unset($addressTotalsData[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]);
$quoteTotals = $this->totalsInterfaceFactory->create();
$this->dataObjectHelper->populateWithArray(
$quoteTotals,
$addressTotalsData,
TotalsInterface::class
);
$items = array_map([$this->itemConverter, 'modelToDataObject'], $quote->getAllVisibleItems());
// $logger = ObjectManager::getInstance()->get(LoggerInterface::class);
$calculatedTotals = $this->totalsConverter->process($addressTotals);
$quoteTotals->setTotalSegments($calculatedTotals);
$quoteTotals->setCouponCode($this->couponService->get($cartId));
$quoteTotals->setItems($items);
$quoteTotals->setDiscountAmount($quote->getData('customer_discount'));
$quoteTotals->setItemsQty($quote->getItemsQty());
$quoteTotals->setBaseCurrencyCode($quote->getBaseCurrencyCode());
$quoteTotals->setQuoteCurrencyCode($quote->getQuoteCurrencyCode());
return $quoteTotals;// TODO: Change the autogenerated stub
}
}
@@ -0,0 +1,30 @@
<?php
namespace Stemcell\Checkout\Model\Cart;
use Stemcell\Checkout\Api\Data\Quote\TotalsInterface;
use Stemcell\Checkout\Api\Data\Quote\TotalsItemInterface;
class Totals extends \Magento\Quote\Model\Cart\Totals implements TotalsInterface
{
/**
* Get totals by items
*
* @return TotalsItemInterface[]|null
*/
public function getItems()
{
return $this->getData(self::KEY_ITEMS);
}
/**
* Get totals by items
*
* @param TotalsItemInterface[] $items
* @return $this
*/
public function setItems(array $items = null)
{
return $this->setData(self::KEY_ITEMS, $items);
}
}
@@ -0,0 +1,173 @@
<?php
namespace Stemcell\Checkout\Model\Cart\Totals;
use Magento\Framework\Api\AttributeValueFactory;
use Stemcell\Checkout\Api\Data\Quote\TotalsItemInterface;
use \Magento\Quote\Model\Quote\ItemFactory as QuoteItemFactory;
use \Magento\Quote\Model\Quote\Item as QuoteItem;
use Stemcell\Customer\Api\Data\SalespersonInterface;
use Stemcell\Customer\Model\LabRepository;
class Item extends \Magento\Quote\Model\Cart\Totals\Item implements TotalsItemInterface
{
protected $item = null;
private SalespersonInterface $salespersonInterface;
private LabRepository $labRepository;
private QuoteItemFactory $itemFactory;
public function __construct(
\Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
\Magento\Framework\Api\AttributeValueFactory $attributeValueFactory,
QuoteItemFactory $itemFactory,
SalespersonInterface $salespersonInterface,
LabRepository $labRepository,
$data = []
) {
$this->itemFactory = $itemFactory;
$this->salespersonInterface = $salespersonInterface;
$this->labRepository = $labRepository;
parent::__construct($extensionFactory, $attributeValueFactory, $data);
}
/**
* @return QuoteItem
*/
protected function getQuoteItem()
{
if (!$this->item) {
$this->item = $this->itemFactory->create()->load($this->getItemId());
}
return $this->item;
}
/**
* @inheritDoc
*/
public function getSku()
{
return $this->_get(self::SKU);
}
/**
* @inheritDoc
*/
public function setSku(string $sku)
{
return $this->setData(self::SKU, $this->getQuoteItem()->getSku());
}
/**
* @inheritDoc
*/
public function getSalespersonName()
{
return $this->_get(self::SALESPERSON_NAME);
}
/**
* @inheritDoc
*/
public function setSalespersonName(string | null $salespersonName)
{
return $this->setData(self::SALESPERSON_NAME, $salespersonName);
}
/**
* @inheritDoc
*/
public function getLabBookingAccount()
{
return $this->_get(self::LAB_BOOKING_ACCOUNT);
}
/**
* @inheritDoc
*/
public function setLabBookingAccount(string $labBookingAccount)
{
return $this->setData(self::LAB_BOOKING_ACCOUNT, $labBookingAccount);
}
/**
* @inheritDoc
*/
public function getCdCode()
{
return $this->_get(self::CD_CODE);
}
/**
* @inheritDoc
*/
public function setCdCode(string $cdCode)
{
return $this->setData(self::CD_CODE, $this->getQuoteItem()->getCd());
}
/**
* @inheritDoc
*/
public function getQuoteCode()
{
return $this->_get(self::QUOTE_CODE);
}
/**
* @inheritDoc
*/
public function setQuoteCode(string $quoteCode)
{
return $this->setData(self::QUOTE_CODE, $this->getQuoteItem()->getData('quote'));
}
/**
* @inheritDoc
*/
public function getPiSapId()
{
return $this->_get(self::PI_SAP_ID);
}
/**
* @inheritDoc
*/
public function setPiSapId(string $piSapId)
{
return $this->setData(self::PI_SAP_ID, $this->getQuoteItem()->getData(self::PI_SAP_ID));
}
/**
* @inheritDoc
*/
public function getCustomerDiscountPercent()
{
return $this->_get(self::CUSTOMER_DISCOUNT_PERCENT);
}
/**
* @inheritDoc
*/
public function setCustomerDiscountPercent(string $customerDiscountPercent)
{
return $this->setData(self::CUSTOMER_DISCOUNT_PERCENT, $customerDiscountPercent);
}
/**
* @inheritDoc
*/
public function getNote()
{
return $this->_get(self::NOTE);
}
/**
* @inheritDoc
*/
public function setNote(string $note)
{
return $this->setData(self::NOTE, $note);
}
}
@@ -0,0 +1,129 @@
<?php
namespace Stemcell\Checkout\Model\Cart\Totals;
use Magento\Catalog\Helper\Product\ConfigurationPool;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\ExtensibleDataInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Magento\Framework\Exception\LocalizedException;
use Stemcell\Checkout\Api\Data\Quote\TotalsInterfaceFactory;
use Psr\Log\LoggerInterface;
use Stemcell\Customer\Api\SalespersonRepositoryInterface;
use Stemcell\Customer\Model\LabRepository;
class ItemConverter extends \Magento\Quote\Model\Cart\Totals\ItemConverter
{
private SalespersonRepositoryInterface $salespersonRepository;
private LabRepository $labRepository;
public function __construct(
private ConfigurationPool $configurationPool,
private EventManager $eventManager,
private \Stemcell\Checkout\Api\Data\Quote\TotalsItemInterfaceFactory $stemcelltotalsItemFactory,
private \Magento\Quote\Api\Data\TotalsItemInterfaceFactory $totalsItemFactory,
SalespersonRepositoryInterface $salespersonRepository,
LabRepository $labRepository,
private DataObjectHelper $dataObjectHelper,
private \Magento\Framework\Serialize\Serializer\Json $serializer
) {
parent::__construct($configurationPool, $eventManager, $totalsItemFactory, $dataObjectHelper, $serializer);
$this->salespersonRepository = $salespersonRepository;
$this->labRepository = $labRepository;
}
/**
* Retrieve formatted item options view
*
* @param \Magento\Quote\Api\Data\CartItemInterface $item
* @return string
*/
private function getFormattedOptionValue($item)
{
$optionsData = [];
/* @var $helper \Magento\Catalog\Helper\Product\Configuration */
$helper = $this->configurationPool->getByProductType('default');
$options = $this->configurationPool->getByProductType($item->getProductType())->getOptions($item);
foreach ($options as $index => $optionValue) {
$params = [
'max_length' => 55,
'cut_replacer' => ' <a href="#" class="dots tooltip toggle" onclick="return false">...</a>'
];
$option = $helper->getFormattedOptionValue($optionValue, $params);
$optionsData[$index] = $option;
$optionsData[$index]['label'] = $optionValue['label'];
}
return $this->serializer->serialize($optionsData);
}
protected function addAdditionalItemsData(\Magento\Quote\Model\Quote\Item $quoteItem)
{
$data = [];
$data['sku'] = $quoteItem->getSku();
if ($quoteItem->getSalespersonId()) {
$salesperson = $this->salespersonRepository->get($quoteItem->getSalespersonId());
$data['salesperson_name'] = $salesperson->getName();
} else {
$data['salesperson_name'] = '';
}
if ($quoteItem->getLabId()) {
try {
$lab = $this->labRepository->get($quoteItem->getLabId());
$data['lab_booking_account'] = $lab->getBookingAccount();
} catch (LocalizedException $e) {
}
}
$data['cd_code'] = $quoteItem->getCd();
$data['quote_code'] = $quoteItem->getData('quote');
$data['note'] = $quoteItem->getData('note');
$data['pi_sap_id'] = $quoteItem->getData('pi_sap_id');
if ($quoteItem->getData('customer_discount_percent')) {
$data['customer_discount_percent'] = number_format(
$quoteItem->getData('customer_discount_percent')*1.0,
2, '.', ''
).'%';
} else {
$data['customer_discount_percent'] = '';
}
if ($option = $quoteItem->getOptionByCode('simple_product')) {
$data['name'] = $option->getProduct()->getName();
}
return $data;
}
/**
* Converts a specified quote item model to a totals item data object.
*
* @param \Magento\Quote\Model\Quote\Item $item
* @return \Stemcell\Checkout\Api\Data\Quote\TotalsItemInterface
* @throws \Exception
*/
public function modelToDataObject($item)
{
$this->eventManager->dispatch('items_additional_data', ['item' => $item]);
$items = $item->toArray();
$items = array_merge($items, $this->addAdditionalItemsData($item));
$items['options'] = $this->getFormattedOptionValue($item);
// ObjectManager::getInstance()->get(LoggerInterface::class)->debug('modelToDataObject $items', $items);
unset($items[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]);
$itemsData = $this->stemcelltotalsItemFactory->create();
// $itemsData->setSalespersonName();
$itemsData->setItemId($item->getEntityId());
$this->dataObjectHelper->populateWithArray(
$itemsData,
$items,
\Stemcell\Checkout\Api\Data\Quote\TotalsItemInterface::class
);
return $itemsData;
}
}
@@ -0,0 +1,129 @@
<?php
namespace Stemcell\Checkout\Model;
use Magento\Captcha\Api\CaptchaConfigPostProcessorInterface;
use Magento\Catalog\Helper\Product\ConfigurationPool;
use Magento\Checkout\Helper\Data as CheckoutHelper;
use Magento\Checkout\Model\Cart;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Api\CustomerRepositoryInterface as CustomerRepository;
use Magento\Customer\Model\Address\CustomerAddressDataProvider;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Customer\Model\Url as CustomerUrlManager;
use Magento\Eav\Api\AttributeOptionManagementInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Escaper;
use Magento\Framework\Locale\FormatInterface as LocaleFormat;
use Magento\Framework\UrlInterface;
use Magento\Quote\Api\CartItemRepositoryInterface as QuoteItemRepository;
use Magento\Quote\Api\CartTotalRepositoryInterface;
use Magento\Quote\Api\ShippingMethodManagementInterface as ShippingMethodManager;
use Magento\Quote\Model\Cart\Totals\Item;
use Magento\Quote\Model\Quote\ItemFactory;
use Magento\Quote\Model\QuoteIdMaskFactory;
use Stemcell\Customer\Api\SalespersonRepositoryInterface;
use Stemcell\Customer\Model\LabRepository;
class DefaultConfigProvider extends \Magento\Checkout\Model\DefaultConfigProvider
{
/**
* @var CheckoutSession
*/
protected $checkoutSession;
private ItemFactory $quoteItem;
private SalespersonRepositoryInterface $salespersonRepository;
private LabRepository $labRepository;
public function __construct(
CheckoutHelper $checkoutHelper,
CheckoutSession $checkoutSession,
CustomerRepository $customerRepository,
CustomerSession $customerSession,
CustomerUrlManager $customerUrlManager,
HttpContext $httpContext,
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
QuoteItemRepository $quoteItemRepository,
ShippingMethodManager $shippingMethodManager,
ConfigurationPool $configurationPool,
QuoteIdMaskFactory $quoteIdMaskFactory,
LocaleFormat $localeFormat,
\Magento\Customer\Model\Address\Mapper $addressMapper,
\Magento\Customer\Model\Address\Config $addressConfig,
FormKey $formKey,
\Magento\Catalog\Helper\Image $imageHelper,
\Magento\Framework\View\ConfigInterface $viewConfig,
\Magento\Directory\Model\Country\Postcode\ConfigInterface $postCodesConfig,
Cart\ImageProvider $imageProvider,
\Magento\Directory\Helper\Data $directoryHelper,
CartTotalRepositoryInterface $cartTotalRepository,
ScopeConfigInterface $scopeConfig,
\Magento\Shipping\Model\Config $shippingMethodConfig,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Quote\Api\PaymentMethodManagementInterface $paymentMethodManagement,
UrlInterface $urlBuilder,
CaptchaConfigPostProcessorInterface $configPostProcessor,
ItemFactory $quoteItem,
SalespersonRepositoryInterface $salespersonRepository,
LabRepository $labRepository,
AddressMetadataInterface $addressMetadata = null,
AttributeOptionManagementInterface $attributeOptionManager = null,
CustomerAddressDataProvider $customerAddressData = null,
Escaper $escaper = null
)
{
parent::__construct($checkoutHelper, $checkoutSession, $customerRepository, $customerSession, $customerUrlManager, $httpContext, $quoteRepository, $quoteItemRepository, $shippingMethodManager, $configurationPool, $quoteIdMaskFactory, $localeFormat, $addressMapper, $addressConfig, $formKey, $imageHelper, $viewConfig, $postCodesConfig, $imageProvider, $directoryHelper, $cartTotalRepository, $scopeConfig, $shippingMethodConfig, $storeManager, $paymentMethodManagement, $urlBuilder, $configPostProcessor, $addressMetadata, $attributeOptionManager, $customerAddressData, $escaper);
$this->checkoutSession = $checkoutSession;
$this->quoteItem = $quoteItem;
$this->salespersonRepository = $salespersonRepository;
$this->labRepository = $labRepository;
}
protected function addAdditionalItemsData(Item $item)
{
$data = [];
$quoteItem = $this->quoteItem->create()->load($item->getItemId());
$data['sku'] = $quoteItem->getSku();
if ($quoteItem->getSalesPersonId()) {
$salesperson = $this->salespersonRepository->get($quoteItem->getSalesPersonId());
$data['salesperson_name'] = $salesperson->getName();
}
if ($quoteItem->getLabCode()) {
$lab = $this->labRepository->getByLabCode($quoteItem->getLabCode());
$data['booking_account'] = $lab->getBookingAccount();
}
$data['cd_code'] = $quoteItem->getCd();
$data['quote_code'] = $quoteItem->getData('quote');
$data['pi_sap_id'] = $quoteItem->getData('pi_sap_id');
return $data;
}
protected function getTotalsData()
{
/** @var \Magento\Quote\Api\Data\TotalsInterface $totals */
$totals = $this->cartTotalRepository->get($this->checkoutSession->getQuote()->getId());
$items = [];
/** @var Item $item */
foreach ($totals->getItems() as $item) {
$items[] = array_merge($item->__toArray(), $this->addAdditionalItemsData($item));
}
$totalSegmentsData = [];
/** @var \Magento\Quote\Model\Cart\TotalSegment $totalSegment */
foreach ($totals->getTotalSegments() as $totalSegment) {
$totalSegmentArray = $totalSegment->toArray();
if (is_object($totalSegment->getExtensionAttributes())) {
$totalSegmentArray['extension_attributes'] = $totalSegment->getExtensionAttributes()->__toArray();
}
$totalSegmentsData[] = $totalSegmentArray;
}
$totals->setItems($items);
$totals->setTotalSegments($totalSegmentsData);
$totalsArray = $totals->toArray();
if (is_object($totals->getExtensionAttributes())) {
$totalsArray['extension_attributes'] = $totals->getExtensionAttributes()->__toArray();
}
return $totalsArray;
}
}
@@ -0,0 +1,45 @@
<?php
namespace Stemcell\Checkout\Observer;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;
class ApplyCustomerDiscount implements ObserverInterface
{
private RequestInterface $request;
public function __construct(
RequestInterface $request
) {
$this->request = $request;
}
/**
* @param \Magento\Quote\Model\Quote\Item $item
* @return $this
*/
protected function getDiscountPercent(\Magento\Quote\Model\Quote\Item $item)
{
$cartData = $this->request->getParam('cart');
if (isset($cartData[$item->getId()]['customer_discount_percent'])) {
$discount = floatval($cartData[$item->getId()]['customer_discount_percent']);
$item->setCustomerDiscountPercent($discount);
}
return $this;
}
public function execute(Observer $observer)
{
/* @var $cart \Magento\Checkout\Model\Cart */
$cart = $observer->getCart();
$logger = ObjectManager::getInstance()->get(LoggerInterface::class);
foreach ($cart->getItems() as $item) {
/* @var $item \Magento\Quote\Model\Quote\Item */
$this->getDiscountPercent($item);
}
}
}
@@ -0,0 +1,56 @@
<?php
namespace Stemcell\Checkout\Observer;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;
class FieldCopy implements ObserverInterface
{
protected $objectCopyService;
private \Magento\Quote\Model\ResourceModel\Quote\Item\Collection $quoteItemCollection;
public function __construct(
\Magento\Framework\DataObject\Copy $objectCopyService,
\Magento\Quote\Model\ResourceModel\Quote\Item\Collection $quoteItemCollection
) {
$this->objectCopyService = $objectCopyService;
$this->quoteItemCollection = $quoteItemCollection;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
/* @var $order \Magento\Sales\Model\Order */
$order = $observer->getEvent()->getData('order');
/* @var $quote \Magento\Quote\Model\Quote */
$quote = $observer->getEvent()->getData('quote');
$order->setData('customer_discount', $quote->getData('customer_discount'));
$order->setData('salesperson_id', $quote->getData('salesperson_id'));
$order->setDiscountAmount($quote->getData('discount_amount') + $order->getDiscountAmount());
$orderItems = $order->getItems();
$quoteItemsId = $items = [];
foreach ($orderItems as $item) {
$quoteItemsId[] = $item->getQuoteItemId();
}
$quoteItems = $this->quoteItemCollection->addFieldToFilter('item_id', ['in'=>$quoteItemsId])
->setItemObjectClass(\Magento\Quote\Model\Quote\Item::class)
->load();
foreach ($quoteItems as $item) {
/* @var $item \Magento\Quote\Model\Quote\Item */
$items[$item->getItemId()] = $item;
}
$fields = ['lab_id', 'lab_code', 'pi_sap_id', 'cd', 'quote', 'pi', 'company', 'user', 'user_tel',
'user_email', 'note', 'user_type', 'customer_discount_percent', 'salesperson_id', 'item_sort'
];
foreach ($orderItems as $item) {
foreach ($fields as $field) {
$item->setData($field, $items[$item->getQuoteItemId()]->getData($field));
}
}
return $this;
}
}
+51
View File
@@ -0,0 +1,51 @@
# Mage2 Module Stemcell Checkout
``stemcell/module-checkout``
- [Main Functionalities](#markdown-header-main-functionalities)
- [Installation](#markdown-header-installation)
- [Configuration](#markdown-header-configuration)
- [Specifications](#markdown-header-specifications)
- [Attributes](#markdown-header-attributes)
## Main Functionalities
extension of Magento Checkout
## Installation
\* = in production please use the `--keep-generated` option
### Type 1: Zip file
- Unzip the zip file in `app/code/Stemcell`
- Enable the module by running `php bin/magento module:enable Stemcell_Checkout`
- Apply database updates by running `php bin/magento setup:upgrade`\*
- Flush the cache by running `php bin/magento cache:flush`
### Type 2: Composer
- Make the module available in a composer repository for example:
- private repository `repo.magento.com`
- public repository `packagist.org`
- public github repository as vcs
- Add the composer repository to the configuration by running `composer config repositories.repo.magento.com composer https://repo.magento.com/`
- Install the module composer by running `composer require stemcell/module-checkout`
- enable the module by running `php bin/magento module:enable Stemcell_Checkout`
- apply database updates by running `php bin/magento setup:upgrade`\*
- Flush the cache by running `php bin/magento cache:flush`
## Configuration
## Specifications
## Attributes
+22
View File
@@ -0,0 +1,22 @@
{
"name": "stemcell/module-checkout",
"description": "extension of Magento Checkout",
"type": "magento2-module",
"license": "proprietary",
"authors": [
{
"name": "Liang Feng",
"email": "344531331@qq.com"
}
],
"minimum-stability": "dev",
"require": {},
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Stemcell\\Checkout\\": ""
}
}
}
@@ -0,0 +1,65 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="quote">
<column xsi:type="int" name="salesperson_id" unsigned="true" nullable="true" identity="false"
default="0" comment="Salesperson ID"/>
<column xsi:type="decimal" name="customer_discount" unsigned="false" nullable="true"
default="0" scale="2" comment="customer discount"/>
</table>
<table name="quote_item" resource="checkout" engine="innodb" comment="Sales Flat Quote Item">
<column xsi:type="int" name="lab_id" unsigned="true" nullable="false" comment="Lab Code"/>
<column xsi:type="varchar" name="lab_code" nullable="false" length="255" comment="Lab Code"/>
<column xsi:type="varchar" name="pi_sap_id" nullable="false" length="255" comment="Lab PI SAP ID"/>
<column xsi:type="int" name="salesperson_id" unsigned="true" nullable="true" identity="false"
default="0" comment="Salesperson ID"/>
<column xsi:type="varchar" name="cd" nullable="false" length="255" comment="CD"/>
<column xsi:type="varchar" name="quote" nullable="false" length="255" comment="Quote"/>
<column xsi:type="decimal" name="customer_discount_percent" scale="4" precision="12" unsigned="true"
nullable="false" default="0" comment="用户在购物车中填写的折扣"/>
<column xsi:type="varchar" name="pi" nullable="false" length="255" comment="PI"/>
<column xsi:type="varchar" name="company" nullable="false" length="255" comment="最终用户单位"/>
<column xsi:type="varchar" name="user" nullable="false" length="255" comment="最终使用人"/>
<column xsi:type="varchar" name="user_tel" nullable="false" length="255" comment="最终使用人电话"/>
<column xsi:type="varchar" name="user_email" nullable="false" length="255" comment="最终使用人邮箱"/>
<column xsi:type="varchar" name="note" nullable="false" length="255" comment="备注"/>
<column xsi:type="smallint" name="user_type" nullable="false" comment="终端类型: 终端、二级经销商"/>
<column xsi:type="int" name="item_sort" unsigned="true" nullable="true" identity="false"
default="0" comment="Item Sort"/>
</table>
<table name="sales_order">
<column xsi:type="int" name="salesperson_id" unsigned="true" nullable="true" identity="false"
default="0" comment="Salesperson ID"/>
<column xsi:type="decimal" name="customer_discount" unsigned="false" nullable="true" scale="2"
default="0" comment="customer discount"/>
</table>
<table name="sales_order_item" resource="checkout" engine="innodb" comment="Sales Flat Quote Item">
<column xsi:type="int" name="lab_id" unsigned="true" nullable="false" comment="Lab Code"/>
<column xsi:type="varchar" name="lab_code" nullable="false" length="255" comment="Lab Code"/>
<column xsi:type="varchar" name="pi_sap_id" nullable="false" length="255" comment="Lab PI SAP ID"/>
<column xsi:type="int" name="salesperson_id" unsigned="true" nullable="true" identity="false"
default="0" comment="Salesperson ID"/>
<column xsi:type="varchar" name="cd" nullable="false" length="255" comment="CD"/>
<column xsi:type="varchar" name="quote" nullable="false" length="255" comment="Quote"/>
<column xsi:type="decimal" name="customer_discount_percent" scale="4" precision="12" unsigned="true"
nullable="false" default="0" comment="用户在购物车中填写的折扣"/>
<column xsi:type="varchar" name="pi" nullable="false" length="255" comment="PI"/>
<column xsi:type="varchar" name="company" nullable="false" length="255" comment="最终用户单位"/>
<column xsi:type="varchar" name="user" nullable="false" length="255" comment="最终使用人"/>
<column xsi:type="varchar" name="user_tel" nullable="false" length="255" comment="最终使用人电话"/>
<column xsi:type="varchar" name="user_email" nullable="false" length="255" comment="最终使用人邮箱"/>
<column xsi:type="varchar" name="note" nullable="false" length="255" comment="备注"/>
<column xsi:type="smallint" name="user_type" nullable="false" comment="终端类型: 终端、二级经销商"/>
<column xsi:type="int" name="item_sort" unsigned="true" nullable="true" identity="false"
default="0" comment="Item Sort"/>
</table>
</schema>
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Checkout\Block\Cart\Item\Renderer" type="Stemcell\Checkout\Block\Cart\Item\Renderer" />
<preference for="\Magento\Checkout\Model\Cart" type="Stemcell\Checkout\Model\Cart" />
<preference for="\Magento\Bundle\Helper\Catalog\Product\Configuration" type="Stemcell\Checkout\Helper\Catalog\Product\Configuration" />
<preference for="Stemcell\Checkout\Api\Data\Quote\TotalsItemInterface" type="Stemcell\Checkout\Model\Cart\Totals\Item" />
<preference for="Stemcell\Checkout\Api\Data\Quote\TotalsInterface" type="Stemcell\Checkout\Model\Cart\Totals" />
<preference for="Stemcell\Checkout\Api\CartTotalRepositoryInterface" type="Stemcell\Checkout\Model\Cart\CartTotalRepository" />
<type name="Magento\Quote\Model\Cart\CartTotalRepository">
<arguments>
<argument name="converter" xsi:type="object">Stemcell\Checkout\Model\Cart\Totals\ItemConverter</argument>
</arguments>
</type>
<type name="Stemcell\Checkout\Model\Cart\CartTotalRepository">
<arguments>
<argument name="converter" xsi:type="object">Stemcell\Checkout\Model\Cart\Totals\ItemConverter</argument>
</arguments>
</type>
</config>
@@ -0,0 +1,8 @@
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_model_service_quote_submit_before">
<observer name="stemcell_checkout_sales_model_service_quote_submit_before" instance="Stemcell\Checkout\Observer\FieldCopy" />
</event>
<event name="checkout_cart_save_before">
<observer name="customer_discount_persistent" instance="Stemcell\Checkout\Observer\ApplyCustomerDiscount" />
</event>
</config>
@@ -0,0 +1,48 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
<extension_attributes for="Magento\Quote\Api\Data\CartInterface">
<attribute code="salesperson_id" type="int" />
<attribute code="customer_discount" type="float" />
</extension_attributes>
<extension_attributes for="Magento\Quote\Api\Data\CartItemInterface">
<attribute code="lab_id" type="int" />
<attribute code="lab_code" type="string" />
<attribute code="pi_sap_id" type="string" />
<attribute code="cd" type="string" />
<attribute code="quote" type="string" />
<attribute code="pi" type="string" />
<attribute code="company" type="string" />
<attribute code="user" type="string" />
<attribute code="user_tel" type="string" />
<attribute code="user_email" type="string" />
<attribute code="note" type="string" />
<attribute code="user_type" type="int" />
</extension_attributes>
<extension_attributes for="Magento\Sales\Api\Data\OrderInterface">
<attribute code="salesperson_id" type="int" />
<attribute code="customer_discount" type="float" />
</extension_attributes>
<extension_attributes for="Magento\Sales\Api\Data\OrderItemInterface">
<attribute code="lab_id" type="int" />
<attribute code="lab_code" type="string" />
<attribute code="pi_sap_id" type="string" />
<attribute code="cd" type="string" />
<attribute code="quote" type="string" />
<attribute code="pi" type="string" />
<attribute code="company" type="string" />
<attribute code="user" type="string" />
<attribute code="user_tel" type="string" />
<attribute code="user_email" type="string" />
<attribute code="note" type="string" />
<attribute code="user_type" type="int" />
</extension_attributes>
</config>
@@ -0,0 +1,55 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:DataObject/etc/fieldset.xsd">
<scope id="global">
<fieldset id="sales_convert_quote">
<field name="salesperson_id">
<aspect name="to_order" />
</field>
</fieldset>
<fieldset id="quote_convert_item">
<field name="lab_id">
<aspect name="to_order_item" />
</field>
<field name="lab_code">
<aspect name="to_order_item" />
</field>
<field name="pi_sap_id">
<aspect name="to_order_item" />
</field>
<field name="cd">
<aspect name="to_order_item" />
</field>
<field name="quote">
<aspect name="to_order_item" />
</field>
<field name="pi">
<aspect name="to_order_item" />
</field>
<field name="company">
<aspect name="to_order_item" />
</field>
<field name="user">
<aspect name="to_order_item" />
</field>
<field name="user_tel">
<aspect name="to_order_item" />
</field>
<field name="user_email">
<aspect name="to_order_item" />
</field>
<field name="note">
<aspect name="to_order_item" />
</field>
<field name="user_type">
<aspect name="to_order_item" />
</field>
</fieldset>
</scope>
</config>
@@ -0,0 +1,14 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="stemcell_checkout" frontName="stemcell_checkout">
<module name="Stemcell_Checkout" />
</route>
</router>
</config>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Stemcell_Checkout">
<sequence>
<module name="Magento_Checkout"/>
<module name="Magento_Quote"/>
</sequence>
</module>
</config>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<!-- Managing My Cart Total -->
<route url="/V1/carts/mine/totals" method="GET">
<service class="Stemcell\Checkout\Api\CartTotalRepositoryInterface" method="get"/>
<resources>
<resource ref="self" />
</resources>
<data>
<parameter name="cartId" force="true">%cart_id%</parameter>
</data>
</route>
</routes>
@@ -0,0 +1,5 @@
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Stemcell_Checkout', __DIR__);