Commit 18747450 authored by Jonathan Sacksick's avatar Jonathan Sacksick Committed by Jonathan Sacksick
Browse files

Issue #3307069 by jsacksick: [BuyXGetY] Remove automatically added order items...

Issue #3307069 by jsacksick: [BuyXGetY] Remove automatically added order items if the promotion no longer applies from the promotion order processor.
parent 377432d1
Loading
Loading
Loading
Loading
+13 −0
Changes for modules/promotion/src/PromotionOrderProcessor.php: 13 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -5,6 +5,7 @@ namespace Drupal\commerce_promotion;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\OrderPreprocessorInterface;
use Drupal\commerce_order\OrderProcessorInterface;
use Drupal\commerce_price\Calculator;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
@@ -137,6 +138,18 @@ class PromotionOrderProcessor implements OrderPreprocessorInterface, OrderProces
      }
      $promotion->apply($order);
    }
    // Cleanup order items added by the BuyXGetY offer in case the promotion
    // no longer applies.
    foreach ($order->getItems() as $order_item) {
      if (!$order_item->getData('owned_by_promotion', FALSE)) {
        continue;
      }
      // Remove order items which had their quantities set to 0.
      if (Calculator::compare($order_item->getQuantity(), '0') === 0) {
        $order->removeItem($order_item);
        $order_item->delete();
      }
    }
  }

}
+26 −0
Changes for modules/promotion/tests/src/Kernel/PromotionOrderProcessorTest.php: 26 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -334,6 +334,32 @@ class PromotionOrderProcessorTest extends OrderKernelTestBase {
    $this->assertEquals('Promotion EN', $adjustments[0]->getLabel());
  }

  /**
   * Tests that the promotion order processor cleans up auto added order items.
   */
  public function testOrderItemRemoval() {
    // We simulate an order item automatically added by the BuyXGetY offer.
    $order_item = OrderItem::create([
      'type' => 'test',
      'quantity' => 0,
      'unit_price' => [
        'number' => '20.00',
        'currency_code' => 'USD',
      ],
      'data' => [
        'owned_by_promotion' => TRUE,
      ],
    ]);
    $order_item->save();
    $this->order->setRefreshState(Order::REFRESH_SKIP);
    $this->order->addItem($order_item);
    $this->order->save();

    $this->assertCount(1, $this->order->getItems());
    $this->container->get('commerce_promotion.promotion_order_processor')->process($this->order);
    $this->assertCount(0, $this->order->getItems());
  }

  /**
   * Changes the active language for translations.
   *