custom/plugins/CompraEnvironmentalDiscountSW6/src/Core/System/EnvironmentalDiscountService.php line 182

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Compra\EnvironmentalDiscountSW6\Core\System;
  3. use Shopware\Core\Checkout\Cart\Cart;
  4. use Shopware\Core\Checkout\Cart\CartPersisterInterface;
  5. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  6. use Shopware\Core\Checkout\Cart\Price\AbsolutePriceCalculator;
  7. use Shopware\Core\Checkout\Cart\Price\Struct\AbsolutePriceDefinition;
  8. use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
  9. use Shopware\Core\Checkout\Customer\CustomerEntity;
  10. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  11. use Shopware\Core\System\SystemConfig\SystemConfigService;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Contracts\Translation\TranslatorInterface;
  15. class EnvironmentalDiscountService
  16. {
  17.     public const PLUGIN_PREFIX 'CompraEnvironmentalDiscountSW6.config.';
  18.     public const ENVIRONMENTAL_DISCOUNT_ORDERNUMBER "99999";
  19.     public const INVOICE_DISPATCH_ALWAYS 'mail';
  20.     public const ENVIRONMENTAL_DISCOUT_PRICE_DEFAULT = -0.4;
  21.     /** @var AbsolutePriceCalculator */
  22.     protected $calculator;
  23.     /** @var SystemConfigService */
  24.     protected $systemConfigService;
  25.     /** @var CartPersisterInterface */
  26.     protected $cartPersister;
  27.     /** @var TranslatorInterface */
  28.     protected $translator;
  29.     /** @var Request */
  30.     protected $request;
  31.     public function __construct(
  32.         AbsolutePriceCalculator $calculator,
  33.         SystemConfigService $systemConfigService,
  34.         CartPersisterInterface $cartPersister,
  35.         TranslatorInterface $translator,
  36.         RequestStack $requestStack
  37.     )
  38.     {
  39.         $this->calculator $calculator;
  40.         $this->systemConfigService $systemConfigService;
  41.         $this->cartPersister $cartPersister;
  42.         $this->translator $translator;
  43.         $this->request $requestStack->getCurrentRequest();
  44.     }
  45.     /**
  46.      * Helper function to update the environmental discount cart line item.
  47.      * Checks for customer and invoice dispatch data to decide, whether to add the environmental discount or not.
  48.      *
  49.      * @param Cart $originalCart
  50.      * @param Cart $modifiedCart
  51.      * @param SalesChannelContext $context
  52.      */
  53.     public function updateEnvironmentalDiscount(Cart $originalCartCart $modifiedCartSalesChannelContext $context): void
  54.     {
  55.         $invoicePayments $this->getPluginConfig('invoicePayment');
  56.         $customer $context->getCustomer();
  57.         $currentOption $this->getCurrentOption($customer);
  58.         $customerChangedToMail null;
  59.         $customerInvoiceMailEnabled null;
  60.         $currentPaymentMethod $context->getPaymentMethod();
  61.         $currentPaymentMethodId $currentPaymentMethod->getId();
  62.         // remove environmental discount from line items
  63.         if ($originalCart->getLineItems()->has(self::ENVIRONMENTAL_DISCOUNT_ORDERNUMBER)) {
  64.             $originalCart->getLineItems()->remove(self::ENVIRONMENTAL_DISCOUNT_ORDERNUMBER);
  65.         }
  66.         if ($modifiedCart->getLineItems()->has(self::ENVIRONMENTAL_DISCOUNT_ORDERNUMBER)) {
  67.             $modifiedCart->getLineItems()->remove(self::ENVIRONMENTAL_DISCOUNT_ORDERNUMBER);
  68.         }
  69.         // don't add any environmental discount if no line items in the cart
  70.         if (!$modifiedCart->getLineItems()->first()) {
  71.             return;
  72.         }
  73.         if ($customer) {
  74.             $customFields $customer->getCustomFields();
  75.             if ($customFields && array_key_exists('compra_environmental_discount_has_changed_to_mail'$customFields)) {
  76.                 $customerChangedToMail $customFields['compra_environmental_discount_has_changed_to_mail'];
  77.             }
  78.             if ($customFields && array_key_exists('compra_invoice_mail_enabled'$customFields)) {
  79.                 $customerInvoiceMailEnabled $customFields['compra_invoice_mail_enabled'];
  80.             }
  81.         }
  82.         if (($currentOption === self::INVOICE_DISPATCH_ALWAYS || ($customerChangedToMail && $customerInvoiceMailEnabled))
  83.             && ($invoicePayments && in_array($currentPaymentMethodId$invoicePaymentstrue)
  84.             && $currentPaymentMethod->getActive() && in_array($currentPaymentMethodId$context->getSalesChannel()->getPaymentMethodIds(), true))) {
  85.             /*
  86.              * Add the environmental discount if:
  87.              * - current selected option from session is 'mail'
  88.              * OR
  89.              * - customer actively changed invoice dispatch to 'mail' and 'mail' is still enabled AND
  90.              * - payments for invoice/environmental discount are set AND
  91.              * - current payment method is allowed for environmental discount AND
  92.              * - current payment method is active AND
  93.              * - current payment method is allowed for the current sales channel
  94.              *
  95.              */
  96.             $this->insertEnvironmentalDiscount($originalCart$modifiedCart$context);
  97.         }
  98.         $this->cartPersister->save($modifiedCart$context);
  99.     }
  100.     /**
  101.      * Helper function to modify the cart and insert the environmental discount line item.
  102.      * The discount amount will be collected from the plugin config (if set) or be the default amount,
  103.      * configured as constant from EnvironmentalDiscountService
  104.      *
  105.      * @param Cart $originalCart
  106.      * @param Cart $modifiedCart
  107.      * @param SalesChannelContext $context
  108.      */
  109.     protected function insertEnvironmentalDiscount(Cart $originalCartCart $modifiedCartSalesChannelContext $context): void
  110.     {
  111.         // create discount line item with environmental discount ordernumber as identifier
  112.         $discountLineItem $this->createDiscount(self::ENVIRONMENTAL_DISCOUNT_ORDERNUMBER);
  113.         // get discount amount: abs * -1 will ensure that this will always return a negative value
  114.         $discountAmount = -abs($this->systemConfigService->get(self::PLUGIN_PREFIX 'environmentalDiscount') ?? self::ENVIRONMENTAL_DISCOUT_PRICE_DEFAULT);
  115.         // declare price definition to define how this price is calculated (absolute discount)
  116.         $definition = new AbsolutePriceDefinition(
  117.             $discountAmount
  118.         );
  119.         $discountLineItem->setPriceDefinition($definition);
  120.         // calculate price
  121.         $discountLineItem->setPrice(
  122.             $this->calculator->calculate($definition->getPrice(), $originalCart->getLineItems()->getPrices(), $context)
  123.         );
  124.         // add discount to new cart
  125.         $modifiedCart->add($discountLineItem);
  126.     }
  127.     /**
  128.      * Creates and returns a LineItem for the environmental discount.
  129.      *
  130.      * @param string $name
  131.      * @return LineItem
  132.      */
  133.     protected function createDiscount(string $name): LineItem
  134.     {
  135.         $discountLineItem = new LineItem($nameLineItem::CUSTOM_LINE_ITEM_TYPEnull1);
  136.         // get label for line item by translating the corresponding snippet
  137.         $label $this->translator->trans('compra.environmentalDiscountSW6.discountProductName');
  138.         $discountLineItem->setLabel($label);
  139.         $discountLineItem->setGood(false);
  140.         $discountLineItem->setStackable(false);
  141.         $discountLineItem->setRemovable(false);
  142.         return $discountLineItem;
  143.     }
  144.     /**
  145.      * Helper function to get the current selected invoice dispatch method.
  146.      * If value is set in the session, this will return the session value.
  147.      * Otherwise this will return the invoice dispatch method from the customer.
  148.      *
  149.      * @param CustomerEntity|null $customer
  150.      * @return string|null
  151.      */
  152.     public function getCurrentOption(CustomerEntity $customer null): ?string
  153.     {
  154.         if (!$customer) {
  155.             return $this->request->getSession()->get('compra_environmental_discount_current_option');
  156.         }
  157.         $customerCustomFields $customer->getCustomFields();
  158.         if ($this->request->getSession()->get('compra_environmental_discount_current_option')) {
  159.             return $this->request->getSession()->get('compra_environmental_discount_current_option');
  160.         }
  161.         if (array_key_exists('compra_invoice_mail_enabled'$customerCustomFields)
  162.             && $customerCustomFields['compra_invoice_mail_enabled'] !== null) {
  163.             return $customerCustomFields['compra_invoice_mail_enabled'] ? 'mail' 'post';
  164.         }
  165.         return 'post';
  166.     }
  167.     /**
  168.      * Helper function to set the current invoice dispatch method in the session.
  169.      *
  170.      * @param string $option
  171.      */
  172.     public function setCurrentOption(string $option): void
  173.     {
  174.         $this->request->getSession()->set('compra_environmental_discount_current_option'$option);
  175.     }
  176.     /**
  177.      * Helper function to unset the current invoice dispatch method in the session.
  178.      */
  179.     public function unsetCurrentOption(): void
  180.     {
  181.         $this->request->getSession()->remove('compra_environmental_discount_current_option');
  182.     }
  183.     /**
  184.      * Helper function to get the current invoice dispatch mail address.
  185.      * If value is set in the session, this will return the session value.
  186.      * Otherwise this will return the invoice mail address from the customer.
  187.      *
  188.      * @param CustomerEntity|null $customer
  189.      * @return string|null
  190.      */
  191.     public function getCurrentInvoiceMailAddress(CustomerEntity $customer null): ?string
  192.     {
  193.         if (!$customer) {
  194.             return $this->request->getSession()->get('compra_environmental_discount_current_invoice_mail_address');
  195.         }
  196.         $customerCustomFields $customer->getCustomFields();
  197.         if ($this->request->getSession()->get('compra_environmental_discount_current_invoice_mail_address')) {
  198.             return $this->request->getSession()->get('compra_environmental_discount_current_invoice_mail_address');
  199.         }
  200.         if (array_key_exists('compra_invoice_mail_address'$customerCustomFields)
  201.             && $customerCustomFields['compra_invoice_mail_address'] !== null) {
  202.             return $customerCustomFields['compra_invoice_mail_address'];
  203.         }
  204.         return $customer->getEmail();
  205.     }
  206.     /**
  207.      * Helper function to set the current invoice dispatch mail address in the session.
  208.      *
  209.      * @param string $invoiceMailAddress
  210.      */
  211.     public function setCurrentInvoiceMailAddress(string $invoiceMailAddress): void
  212.     {
  213.         $this->request->getSession()->set('compra_environmental_discount_current_invoice_mail_address'$invoiceMailAddress);
  214.     }
  215.     /**
  216.      * Helper function to unset the current invoice dispatch mail address in the session.
  217.      */
  218.     public function unsetCurrentInvoiceMailAddress(): void
  219.     {
  220.         $this->request->getSession()->remove('compra_environmental_discount_current_invoice_mail_address');
  221.     }
  222.     /**
  223.      * Helper function to get a plugin config from this plugin by a given config name.
  224.      *
  225.      * @param string $name
  226.      * @return mixed
  227.      */
  228.     public function getPluginConfig(string $name)
  229.     {
  230.         return $this->systemConfigService->get(self::PLUGIN_PREFIX $name);
  231.     }
  232. }