You are here

class BuyXGetYTest in Commerce Core 8.2

Tests the "Buy X Get Y" offer.

@coversDefaultClass \Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\BuyXGetY

@group commerce

Hierarchy

Expanded class hierarchy of BuyXGetYTest

File

modules/promotion/tests/src/Kernel/Plugin/Commerce/PromotionOffer/BuyXGetYTest.php, line 22

Namespace

Drupal\Tests\commerce_promotion\Kernel\Plugin\Commerce\PromotionOffer
View source
class BuyXGetYTest extends OrderKernelTestBase {

  /**
   * The test order.
   *
   * @var \Drupal\commerce_order\Entity\OrderInterface
   */
  protected $order;

  /**
   * The test promotion.
   *
   * @var \Drupal\commerce_promotion\Entity\PromotionInterface
   */
  protected $promotion;

  /**
   * The test variations.
   *
   * @var \Drupal\commerce_product\Entity\ProductVariationInterface[]
   */
  protected $variations = [];

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = [
    'commerce_promotion',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() : void {
    parent::setUp();
    $this
      ->installEntitySchema('commerce_promotion');
    $this
      ->installConfig([
      'commerce_promotion',
    ]);
    $this
      ->installSchema('commerce_promotion', [
      'commerce_promotion_usage',
    ]);
    $product_type = ProductType::create([
      'id' => 'test',
      'label' => 'Test',
      'variationType' => 'default',
    ]);
    $product_type
      ->save();
    for ($i = 0; $i < 4; $i++) {
      $this->variations[$i] = ProductVariation::create([
        'type' => 'default',
        'sku' => $this
          ->randomMachineName(),
        'price' => [
          'number' => Calculator::multiply('10', $i + 1),
          'currency_code' => 'USD',
        ],
      ]);
      $this->variations[$i]
        ->save();
    }
    $first_product = Product::create([
      'type' => 'test',
      'title' => $this
        ->randomMachineName(),
      'stores' => [
        $this->store,
      ],
      'variations' => [
        $this->variations[0],
      ],
    ]);
    $first_product
      ->save();
    $second_product = Product::create([
      'type' => 'default',
      'title' => $this
        ->randomMachineName(),
      'stores' => [
        $this->store,
      ],
      'variations' => [
        $this->variations[1],
      ],
    ]);
    $second_product
      ->save();
    $third_product = Product::create([
      'type' => 'default',
      'title' => 'Hat 1',
      'stores' => [
        $this->store,
      ],
      'variations' => [
        $this->variations[2],
      ],
    ]);
    $third_product
      ->save();
    $fourth_product = Product::create([
      'type' => 'default',
      'title' => 'Hat 2',
      'stores' => [
        $this->store,
      ],
      'variations' => [
        $this->variations[3],
      ],
    ]);
    $fourth_product
      ->save();
    $this->order = Order::create([
      'type' => 'default',
      'state' => 'completed',
      'mail' => 'test@example.com',
      'ip_address' => '127.0.0.1',
      'order_number' => '6',
      'uid' => $this
        ->createUser(),
      'store_id' => $this->store,
      'order_items' => [],
    ]);

    // Buy 6 "test" products, get 4 hats.
    $promotion = Promotion::create([
      'name' => 'Promotion 1',
      'order_types' => [
        $this->order
          ->bundle(),
      ],
      'stores' => [
        $this->store
          ->id(),
      ],
      'offer' => [
        'target_plugin_id' => 'order_buy_x_get_y',
        'target_plugin_configuration' => [
          'buy_quantity' => 6,
          'buy_conditions' => [
            [
              'plugin' => 'order_item_product_type',
              'configuration' => [
                'product_types' => [
                  'test',
                ],
              ],
            ],
          ],
          'get_quantity' => 4,
          'get_conditions' => [
            [
              'plugin' => 'order_item_product',
              'configuration' => [
                'products' => [
                  [
                    'product' => $third_product
                      ->uuid(),
                  ],
                  [
                    'product' => $fourth_product
                      ->uuid(),
                  ],
                ],
              ],
            ],
          ],
          'offer_type' => 'fixed_amount',
          'offer_amount' => [
            'number' => '1.00',
            'currency_code' => 'USD',
          ],
        ],
      ],
      'status' => TRUE,
    ]);
    $promotion
      ->save();
    $this->promotion = $this
      ->reloadEntity($promotion);
  }

  /**
   * Tests the non-applicable use cases.
   *
   * @covers ::apply
   */
  public function testNotApplicable() {

    /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
    $order_item_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order_item');
    $first_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      'quantity' => '2',
    ]);
    $first_order_item
      ->save();
    $second_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[1], [
      'quantity' => '4',
    ]);
    $second_order_item
      ->save();
    $this->order
      ->setItems([
      $first_order_item,
      $second_order_item,
    ]);
    $this->order
      ->save();

    // Insufficient purchase quantity.
    // Only the first order item is counted (due to the product type condition),
    // and its quantity is too small (2 < 6).
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    $this
      ->assertEmpty($this->order
      ->collectAdjustments());

    // Sufficient purchase quantity, but no offer order item found.
    $first_order_item
      ->setQuantity(6);
    $first_order_item
      ->save();
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    $this
      ->assertEmpty($this->order
      ->collectAdjustments());
  }

  /**
   * Tests the fixed amount off offer type.
   *
   * @covers ::apply
   */
  public function testFixedAmountOff() {

    /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
    $order_item_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order_item');
    $first_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      'quantity' => '7',
    ]);
    $first_order_item
      ->save();
    $second_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[1], [
      'quantity' => '2',
    ]);

    // Test having a single offer order item, quantity < get_quantity.
    $third_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[2], [
      'quantity' => '3',
    ]);
    $second_order_item
      ->save();
    $this->order
      ->setItems([
      $first_order_item,
      $second_order_item,
      $third_order_item,
    ]);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item, $third_order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertCount(0, $second_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $third_order_item
      ->getAdjustments());
    $adjustments = $third_order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals('Discount', $adjustment
      ->getLabel());
    $this
      ->assertEquals(new Price('-3', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());

    // Test having two offer order items, one ($third_order_item) reduced
    // completely, the other ($fourth_order_item) reduced partially.
    $fourth_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[2], [
      'quantity' => '2',
    ]);
    $this->order
      ->addItem($fourth_order_item);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item, $third_order_item, $fourth_order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertCount(0, $second_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $third_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $fourth_order_item
      ->getAdjustments());
    $adjustments = $third_order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals('Discount', $adjustment
      ->getLabel());
    $this
      ->assertEquals(new Price('-3', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());
    $adjustments = $fourth_order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals('Discount', $adjustment
      ->getLabel());
    $this
      ->assertEquals(new Price('-1', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());
  }

  /**
   * Tests the percentage off offer type.
   *
   * @covers ::apply
   */
  public function testPercentageOff() {
    $offer = $this->promotion
      ->getOffer();
    $offer_configuration = $offer
      ->getConfiguration();
    $offer_configuration['offer_type'] = 'percentage';
    $offer_configuration['offer_percentage'] = '0.1';
    $offer_configuration['offer_amount'] = NULL;
    $offer
      ->setConfiguration($offer_configuration);
    $this->promotion
      ->setOffer($offer);
    $this->promotion
      ->setDisplayName('Buy X Get Y!');

    /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
    $order_item_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order_item');
    $first_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      // Double the buy_quantity -> double the get_quantity.
      'quantity' => '13',
    ]);
    $first_order_item
      ->save();
    $second_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[1], [
      'quantity' => '2',
    ]);

    // Test having a single offer order item, quantity < get_quantity.
    $third_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[2], [
      'quantity' => '6',
    ]);
    $second_order_item
      ->save();
    $this->order
      ->setItems([
      $first_order_item,
      $second_order_item,
      $third_order_item,
    ]);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item, $third_order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertCount(0, $second_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $third_order_item
      ->getAdjustments());
    $adjustments = $third_order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals('Buy X Get Y!', $adjustment
      ->getLabel());
    $this
      ->assertEquals(new Price('-18', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());

    // Test having two offer order items, one ($third_order_item) reduced
    // completely, the other ($fourth_order_item) reduced partially.
    $fourth_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[2], [
      'quantity' => '3',
    ]);
    $this->order
      ->addItem($fourth_order_item);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item, $third_order_item, $fourth_order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertCount(0, $second_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $third_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $fourth_order_item
      ->getAdjustments());
    $adjustments = $third_order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals('Buy X Get Y!', $adjustment
      ->getLabel());
    $this
      ->assertEquals(new Price('-18', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());
    $adjustments = $fourth_order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals('Buy X Get Y!', $adjustment
      ->getLabel());
    $this
      ->assertEquals(new Price('-6', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());
  }

  /**
   * Tests the same order item matching both buy and get conditions.
   *
   * @covers ::apply
   */
  public function testSameOrderItem() {
    $offer = $this->promotion
      ->getOffer();
    $offer_configuration = $offer
      ->getConfiguration();
    $offer_configuration['buy_quantity'] = '1';
    $offer_configuration['buy_conditions'] = [];
    $offer_configuration['get_quantity'] = '1';
    $offer_configuration['get_conditions'] = [];
    $offer
      ->setConfiguration($offer_configuration);
    $this->promotion
      ->setOffer($offer);

    /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
    $order_item_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order_item');

    // '2' buy quantities, '2' get quantities, '1' ignored/irrelevant quantity.
    $order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      'quantity' => '5',
    ]);
    $order_item
      ->save();
    $this->order
      ->addItem($order_item);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(1, $order_item
      ->getAdjustments());
    $adjustments = $order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals(new Price('-2', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());
  }

  /**
   * Tests order item sorting.
   *
   * @covers ::apply
   */
  public function testOrderItemSorting() {

    // First cheapest product gets 50% off.
    $offer = $this->promotion
      ->getOffer();
    $offer_configuration = $offer
      ->getConfiguration();
    $offer_configuration['get_quantity'] = '1';
    $offer_configuration['offer_type'] = 'percentage';
    $offer_configuration['offer_percentage'] = '0.5';
    $offer_configuration['offer_amount'] = NULL;
    $offer
      ->setConfiguration($offer_configuration);
    $this->promotion
      ->setOffer($offer);

    /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
    $order_item_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order_item');
    $first_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      'quantity' => '6',
    ]);
    $first_order_item
      ->save();

    // Both order items match the get_conditions, $third_order_item should be
    // discounted because it is cheaper.
    $second_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[3], [
      'quantity' => '1',
    ]);
    $second_order_item
      ->save();
    $third_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[2], [
      'quantity' => '1',
    ]);
    $third_order_item
      ->save();
    $this->order
      ->setItems([
      $first_order_item,
      $second_order_item,
      $third_order_item,
    ]);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item, $third_order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertCount(0, $second_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $third_order_item
      ->getAdjustments());
  }

  /**
   * Tests order item sorting when a 'get_condition' product has a higher value.
   *
   * @covers ::apply
   */
  public function testOrderItemSortingWithHigherValueGetCondition() {
    $offer = $this->promotion
      ->getOffer();
    $offer_configuration = $offer
      ->getConfiguration();

    // The customer purchases 2 quantities of any product.
    $offer_configuration['buy_quantity'] = '2';
    $offer_configuration['buy_conditions'] = [];

    // The customer receives 1 specific product for free.
    $offer_configuration['get_quantity'] = '1';
    $offer_configuration['get_conditions'] = [
      [
        'plugin' => 'order_item_purchased_entity:commerce_product_variation',
        'configuration' => [
          'entities' => [
            $this->variations[2]
              ->uuid(),
          ],
        ],
      ],
    ];
    $offer_configuration['offer_type'] = 'percentage';
    $offer_configuration['offer_percentage'] = '1';
    $offer_configuration['offer_amount'] = NULL;
    $offer
      ->setConfiguration($offer_configuration);
    $this->promotion
      ->setOffer($offer);

    /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
    $order_item_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order_item');

    // Price of first order item: 10. Matches the first required quantity of the
    // buy condition.
    $first_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      'quantity' => '1',
    ]);
    $first_order_item
      ->save();

    // Price of second order item: 20. Matches the second required quantity of
    // the buy condition.
    $second_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[1], [
      'quantity' => '1',
    ]);
    $second_order_item
      ->save();

    // Price of third order item: 30. Matches the get_conditions, which means
    // that this order item will be discounted 100%. The purpose of this test
    // is to check the case when the get_conditions product has an equal or
    // higher value than the order items that match the buy_conditions.
    $third_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[2], [
      'quantity' => '1',
    ]);
    $third_order_item
      ->save();
    $this->order
      ->setItems([
      $first_order_item,
      $second_order_item,
      $third_order_item,
    ]);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item, $third_order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertCount(0, $second_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $third_order_item
      ->getAdjustments());
    $adjustments = $third_order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals(new Price('-30', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());
  }

  /**
   * Tests working with decimal quantities.
   *
   * @covers ::apply
   */
  public function testDecimalQuantities() {

    /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
    $order_item_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order_item');
    $first_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      'quantity' => '2.5',
    ]);
    $first_order_item
      ->save();
    $second_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      'quantity' => '3.5',
    ]);
    $second_order_item
      ->save();
    $third_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[2], [
      'quantity' => '1.5',
    ]);
    $third_order_item
      ->save();
    $fourth_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[2], [
      'quantity' => '5.5',
    ]);
    $fourth_order_item
      ->save();
    $this->order
      ->setItems([
      $first_order_item,
      $second_order_item,
      $third_order_item,
      $fourth_order_item,
    ]);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item, $third_order_item, $fourth_order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertCount(0, $second_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $third_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $fourth_order_item
      ->getAdjustments());
    $adjustments = $third_order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals(new Price('-1.5', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());
    $adjustments = $fourth_order_item
      ->getAdjustments();
    $adjustment = reset($adjustments);
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals(new Price('-2.5', 'USD'), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());
  }

  /**
   * Tests the 'auto-add' offered item capability.
   *
   * @covers ::apply
   */
  public function testAutoAddOrderItem() {

    // Configure a "buy 3 of anything, get 1 specific product free" offer.
    $offer = $this->promotion
      ->getOffer();
    $offer_configuration = $offer
      ->getConfiguration();

    // The customer purchases 3 quantities of any product.
    $offer_configuration['buy_quantity'] = '3';
    $offer_configuration['buy_conditions'] = [];

    // The customer receives 1 specific product for free.
    $offer_configuration['get_quantity'] = '1';
    $offer_configuration['get_conditions'] = [
      [
        'plugin' => 'order_item_purchased_entity:commerce_product_variation',
        'configuration' => [
          'entities' => [
            $this->variations[2]
              ->uuid(),
          ],
        ],
      ],
    ];
    $offer_configuration['get_auto_add'] = TRUE;
    $offer_configuration['offer_type'] = 'percentage';
    $offer_configuration['offer_percentage'] = '1';
    $offer_configuration['offer_amount'] = NULL;
    $offer
      ->setConfiguration($offer_configuration);
    $this->promotion
      ->setOffer($offer);

    /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
    $order_item_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order_item');

    // Price of first order item: 10. Matches the first required quantity of the
    // buy condition.
    $first_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      'quantity' => '3',
    ]);
    $this->order
      ->setItems([
      $first_order_item,
    ]);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);

    // The offer automatically added a second order item.
    list($first_order_item, $second_order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertCount(1, $second_order_item
      ->getAdjustments());
    $this
      ->assertEquals(1, $second_order_item
      ->getQuantity());
    $this
      ->assertEquals($this->variations[2]
      ->id(), $second_order_item
      ->getPurchasedEntityId());
    $this
      ->assertAdjustmentPrice($second_order_item
      ->getAdjustments()[0], '-30');

    // Increase the quantity of the "buy" product to 4, the quantity of the
    // offered product will not change.
    $first_order_item
      ->setQuantity(4);
    $this->order
      ->setItems([
      $first_order_item,
      $second_order_item,
    ]);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item) = $this->order
      ->getItems();
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertEquals(4, $first_order_item
      ->getQuantity());
    $this
      ->assertCount(1, $second_order_item
      ->getAdjustments());
    $this
      ->assertEquals(1, $second_order_item
      ->getQuantity());

    // Increase the quantity of the "buy" product to 6, the quantity of the
    // offered product will be increased to 2.
    $first_order_item
      ->setQuantity(6);
    $this->order
      ->setItems([
      $first_order_item,
      $second_order_item,
    ]);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item) = $this->order
      ->getItems();
    $this
      ->assertEquals(6, $first_order_item
      ->getQuantity());
    $this
      ->assertCount(0, $first_order_item
      ->getAdjustments());
    $this
      ->assertEquals(2, $second_order_item
      ->getQuantity());
    $this
      ->assertCount(1, $second_order_item
      ->getAdjustments());
    $this
      ->assertAdjustmentPrice($second_order_item
      ->getAdjustments()[0], '-60');

    // Try to remove the "get" product from the order, it will be added back
    // automatically.
    $this->order
      ->removeItem($second_order_item);
    $this
      ->assertCount(1, $this->order
      ->getItems());
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item) = $this->order
      ->getItems();
    $this
      ->assertEquals(6, $first_order_item
      ->getQuantity());
    $this
      ->assertEquals(2, $second_order_item
      ->getQuantity());
    $this
      ->assertCount(1, $second_order_item
      ->getAdjustments());
    $this
      ->assertAdjustmentPrice($second_order_item
      ->getAdjustments()[0], '-60');

    // Decrease the quantity of the "buy" product from the order, the "get"
    // quantity will be decreased and the discount will only be applied once.
    $first_order_item
      ->setQuantity(5);
    $this->order
      ->setItems([
      $first_order_item,
      $second_order_item,
    ]);
    $this->order
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item) = $this->order
      ->getItems();
    $this
      ->assertEquals(5, $first_order_item
      ->getQuantity());
    $this
      ->assertEquals(1, $second_order_item
      ->getQuantity());
    $this
      ->assertCount(1, $second_order_item
      ->getAdjustments());
    $this
      ->assertAdjustmentPrice($second_order_item
      ->getAdjustments()[0], '-30');

    // Test that the order item data key holding the auto-added quantity is
    // cleared when the get order item is no longer eligible for the offer, but
    // extra quantity was added by the customer.
    $this
      ->assertNotNull($second_order_item
      ->getData('promotion:1:auto_add_quantity'));
    $second_order_item
      ->setQuantity('2');
    $first_order_item
      ->setQuantity('1');
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list(, $second_order_item) = $this->order
      ->getItems();
    $this
      ->assertNull($second_order_item
      ->getData('promotion:1:auto_add_quantity'));
    $this
      ->assertEquals(1, $second_order_item
      ->getQuantity());
  }

  /**
   * Tests that the auto-added get order item is automatically removed.
   *
   * @covers ::apply
   * @covers ::clear
   */
  public function testAutoRemoveOrderItem() {
    $offer = $this->promotion
      ->getOffer();
    $offer_configuration = $offer
      ->getConfiguration();
    $offer_configuration['buy_quantity'] = '1';
    $offer_configuration['buy_conditions'] = [
      [
        'plugin' => 'order_item_purchased_entity:commerce_product_variation',
        'configuration' => [
          'entities' => [
            $this->variations[0]
              ->uuid(),
          ],
        ],
      ],
    ];

    // The customer receives 1 specific product for free.
    $offer_configuration['get_quantity'] = '1';
    $offer_configuration['get_conditions'] = [
      [
        'plugin' => 'order_item_purchased_entity:commerce_product_variation',
        'configuration' => [
          'entities' => [
            $this->variations[1]
              ->uuid(),
          ],
        ],
      ],
    ];
    $offer_configuration['get_auto_add'] = TRUE;
    $offer_configuration['offer_type'] = 'percentage';
    $offer_configuration['offer_percentage'] = '1';
    $offer_configuration['offer_amount'] = NULL;
    $offer
      ->setConfiguration($offer_configuration);
    $this->promotion
      ->setOffer($offer);
    $this->promotion
      ->set('conditions', [
      [
        'target_plugin_id' => 'order_total_price',
        'target_plugin_configuration' => [
          'operator' => '>=',
          'amount' => [
            'number' => '15.00',
            'currency_code' => 'USD',
          ],
        ],
      ],
    ]);
    $this->promotion
      ->save();
    $this->variations[1]
      ->setPrice(new Price('15', 'USD'))
      ->save();

    /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
    $order_item_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order_item');
    $first_order_item = $order_item_storage
      ->createFromPurchasableEntity($this->variations[0], [
      'quantity' => '2',
    ]);
    $first_order_item
      ->save();
    $this->order
      ->setItems([
      $first_order_item,
    ]);
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    list($first_order_item, $second_order_item) = $this->order
      ->getItems();
    $this
      ->assertEquals(2, $first_order_item
      ->getQuantity());
    $this
      ->assertEquals(2, $second_order_item
      ->getQuantity());
    $this
      ->assertCount(1, $second_order_item
      ->getAdjustments());
    $this
      ->assertAdjustmentPrice($second_order_item
      ->getAdjustments()[0], '-30');
    $first_order_item
      ->setQuantity('1');
    $first_order_item
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    $this
      ->assertCount(1, $this->order
      ->getItems());
    $this
      ->assertEquals(new Price('10', 'USD'), $this->order
      ->getTotalPrice());

    // Test that a promotion that is no longer applicable is also cleared out.
    $first_order_item
      ->setQuantity('2');
    $first_order_item
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    $this
      ->assertCount(2, $this->order
      ->getItems());
    $this->promotion
      ->setEnabled(FALSE);
    $this->promotion
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    $this
      ->assertCount(1, $this->order
      ->getItems());

    // Test that a free auto-added order item is automatically cleared out when
    // the promotion offer no longer applies.
    $this->promotion
      ->setEnabled(TRUE);
    $this->promotion
      ->save();
    $this->variations[1]
      ->setPrice(new Price('0', 'USD'));
    $this->variations[1]
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    $order_items = $this->order
      ->getItems();
    $this
      ->assertCount(2, $order_items);
    $this
      ->assertEquals(new Price('0', 'USD'), $order_items[1]
      ->getUnitPrice());

    // Disable the promotion, since it no longer applies, the auto-added "get"
    // order item should be removed.
    $this->promotion
      ->setEnabled(FALSE);
    $this->promotion
      ->save();
    $this->container
      ->get('commerce_order.order_refresh')
      ->refresh($this->order);
    $order_items = $this->order
      ->getItems();
    $this
      ->assertCount(1, $order_items);
    $this
      ->assertEquals(new Price('20', 'USD'), $order_items[0]
      ->getTotalPrice());
  }

  /**
   * Asserts that a promotion adjustment has the expected price.
   *
   * @param \Drupal\commerce_order\Adjustment $adjustment
   *   The adjustment to test.
   * @param string $price
   *   The expected price, as a string.
   * @param string $currency_code
   *   The expected currency code.
   */
  protected function assertAdjustmentPrice(Adjustment $adjustment, $price, $currency_code = 'USD') {
    $this
      ->assertEquals('promotion', $adjustment
      ->getType());
    $this
      ->assertEquals(new Price($price, $currency_code), $adjustment
      ->getAmount());
    $this
      ->assertEquals($this->promotion
      ->id(), $adjustment
      ->getSourceId());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AssertContentTrait::$content protected property The current raw content.
AssertContentTrait::$drupalSettings protected property The drupalSettings value from the current raw $content.
AssertContentTrait::$elements protected property The XML structure parsed from the current raw $content. 1
AssertContentTrait::$plainTextContent protected property The plain-text content of raw $content (text nodes).
AssertContentTrait::assertEscaped protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertContentTrait::assertField protected function Asserts that a field exists with the given name or ID.
AssertContentTrait::assertFieldById protected function Asserts that a field exists with the given ID and value.
AssertContentTrait::assertFieldByName protected function Asserts that a field exists with the given name and value.
AssertContentTrait::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
AssertContentTrait::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
AssertContentTrait::assertFieldsByValue protected function Asserts that a field exists in the current page with a given Xpath result.
AssertContentTrait::assertLink protected function Passes if a link with the specified label is found.
AssertContentTrait::assertLinkByHref protected function Passes if a link containing a given href (part) is found.
AssertContentTrait::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
AssertContentTrait::assertNoEscaped protected function Passes if the raw text IS NOT found escaped on the loaded page, fail otherwise.
AssertContentTrait::assertNoField protected function Asserts that a field does not exist with the given name or ID.
AssertContentTrait::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
AssertContentTrait::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
AssertContentTrait::assertNoFieldByXPath protected function Asserts that a field does not exist or its value does not match, by XPath.
AssertContentTrait::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
AssertContentTrait::assertNoLink protected function Passes if a link with the specified label is not found.
AssertContentTrait::assertNoLinkByHref protected function Passes if a link containing a given href (part) is not found.
AssertContentTrait::assertNoLinkByHrefInMainRegion protected function Passes if a link containing a given href is not found in the main region.
AssertContentTrait::assertNoOption protected function Asserts that a select option in the current page does not exist.
AssertContentTrait::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
AssertContentTrait::assertNoPattern protected function Triggers a pass if the perl regex pattern is not found in raw content.
AssertContentTrait::assertNoRaw protected function Passes if the raw text is NOT found on the loaded page, fail otherwise.
AssertContentTrait::assertNoText protected function Passes if the page (with HTML stripped) does not contains the text.
AssertContentTrait::assertNoTitle protected function Pass if the page title is not the given string.
AssertContentTrait::assertNoUniqueText protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
AssertContentTrait::assertOption protected function Asserts that a select option in the current page exists.
AssertContentTrait::assertOptionByText protected function Asserts that a select option with the visible text exists.
AssertContentTrait::assertOptionSelected protected function Asserts that a select option in the current page is checked.
AssertContentTrait::assertOptionSelectedWithDrupalSelector protected function Asserts that a select option in the current page is checked.
AssertContentTrait::assertOptionWithDrupalSelector protected function Asserts that a select option in the current page exists.
AssertContentTrait::assertPattern protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertContentTrait::assertRaw protected function Passes if the raw text IS found on the loaded page, fail otherwise.
AssertContentTrait::assertText protected function Passes if the page (with HTML stripped) contains the text.
AssertContentTrait::assertTextHelper protected function Helper for assertText and assertNoText.
AssertContentTrait::assertTextPattern protected function Asserts that a Perl regex pattern is found in the plain-text content.
AssertContentTrait::assertThemeOutput protected function Asserts themed output.
AssertContentTrait::assertTitle protected function Pass if the page title is the given string.
AssertContentTrait::assertUniqueText protected function Passes if the text is found ONLY ONCE on the text version of the page.
AssertContentTrait::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
AssertContentTrait::buildXPathQuery protected function Builds an XPath query.
AssertContentTrait::constructFieldXpath protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertContentTrait::cssSelect protected function Searches elements using a CSS selector in the raw content.
AssertContentTrait::getAllOptions protected function Get all option elements, including nested options, in a select.
AssertContentTrait::getDrupalSettings protected function Gets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::getRawContent protected function Gets the current raw content.
AssertContentTrait::getSelectedItem protected function Get the selected value from a select field.
AssertContentTrait::getTextContent protected function Retrieves the plain-text content from the current raw content.
AssertContentTrait::getUrl protected function Get the current URL from the cURL handler. 1
AssertContentTrait::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
AssertContentTrait::removeWhiteSpace protected function Removes all white-space between HTML tags from the raw content.
AssertContentTrait::setDrupalSettings protected function Sets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::setRawContent protected function Sets the raw content (e.g. HTML).
AssertContentTrait::xpath protected function Performs an xpath search on the contents of the internal browser.
AssertHelperTrait::castSafeStrings protected static function Casts MarkupInterface objects into strings.
AssertLegacyTrait::assert protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertTrue() instead.
AssertLegacyTrait::assertEqual protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertEquals() instead.
AssertLegacyTrait::assertIdentical protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertSame() instead.
AssertLegacyTrait::assertIdenticalObject protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertEquals() instead.
AssertLegacyTrait::assertNotEqual protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertNotEquals() instead.
AssertLegacyTrait::assertNotIdentical protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertNotSame() instead.
AssertLegacyTrait::pass protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertTrue() instead.
AssertLegacyTrait::verbose protected function
BuyXGetYTest::$modules public static property Modules to enable. Overrides OrderKernelTestBase::$modules
BuyXGetYTest::$order protected property The test order.
BuyXGetYTest::$promotion protected property The test promotion.
BuyXGetYTest::$variations protected property The test variations.
BuyXGetYTest::assertAdjustmentPrice protected function Asserts that a promotion adjustment has the expected price.
BuyXGetYTest::setUp protected function Overrides OrderKernelTestBase::setUp
BuyXGetYTest::testAutoAddOrderItem public function Tests the 'auto-add' offered item capability.
BuyXGetYTest::testAutoRemoveOrderItem public function Tests that the auto-added get order item is automatically removed.
BuyXGetYTest::testDecimalQuantities public function Tests working with decimal quantities.
BuyXGetYTest::testFixedAmountOff public function Tests the fixed amount off offer type.
BuyXGetYTest::testNotApplicable public function Tests the non-applicable use cases.
BuyXGetYTest::testOrderItemSorting public function Tests order item sorting.
BuyXGetYTest::testOrderItemSortingWithHigherValueGetCondition public function Tests order item sorting when a 'get_condition' product has a higher value.
BuyXGetYTest::testPercentageOff public function Tests the percentage off offer type.
BuyXGetYTest::testSameOrderItem public function Tests the same order item matching both buy and get conditions.
CommerceKernelTestBase::$store protected property The default store. 1
CommerceKernelTestBase::tearDown protected function Overrides KernelTestBase::tearDown
ConfigTestTrait::configImporter protected function Returns a ConfigImporter object to import test configuration.
ConfigTestTrait::copyConfig protected function Copies configuration objects from source storage to target storage.
DeprecatedServicePropertyTrait::__get public function Allows to access deprecated/removed properties.
DeprecationSuppressionTrait::restoreErrorHandler protected function Restores the original error handler.
DeprecationSuppressionTrait::setErrorHandler protected function Sets an error handler to suppress specified deprecation messages.
EntityKernelTestBase::$deprecatedProperties protected property The list of deprecated services.
EntityKernelTestBase::$entityTypeManager protected property The entity type manager service. 1
EntityKernelTestBase::$generatedIds protected property A list of generated identifiers.
EntityKernelTestBase::$state protected property The state service.
EntityKernelTestBase::createUser protected function Creates a user.
EntityKernelTestBase::generateRandomEntityId protected function Generates a random ID avoiding collisions.
EntityKernelTestBase::getHooksInfo protected function Returns the entity_test hook invocation info.
EntityKernelTestBase::installModule protected function Installs a module and refreshes services.
EntityKernelTestBase::refreshServices protected function Refresh services. 1
EntityKernelTestBase::reloadEntity protected function Reloads the given entity from the storage and returns it.
EntityKernelTestBase::uninstallModule protected function Uninstalls a module and refreshes services.
KernelTestBase::$backupGlobals protected property Back up and restore any global variables that may be changed by tests.
KernelTestBase::$backupStaticAttributes protected property Back up and restore static class properties that may be changed by tests.
KernelTestBase::$backupStaticAttributesBlacklist protected property Contains a few static class properties for performance.
KernelTestBase::$classLoader protected property
KernelTestBase::$configImporter protected property @todo Move into Config test base class. 7
KernelTestBase::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking.
KernelTestBase::$container protected property
KernelTestBase::$databasePrefix protected property
KernelTestBase::$preserveGlobalState protected property Do not forward any global state from the parent process to the processes that run the actual tests.
KernelTestBase::$root protected property The app root.
KernelTestBase::$runTestInSeparateProcess protected property Kernel tests are run in separate processes because they allow autoloading of code from extensions. Running the test in a separate process isolates this behavior from other tests. Subclasses should not override this property.
KernelTestBase::$siteDirectory protected property
KernelTestBase::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 6
KernelTestBase::$vfsRoot protected property The virtual filesystem root directory.
KernelTestBase::assertPostConditions protected function 1
KernelTestBase::bootEnvironment protected function Bootstraps a basic test environment.
KernelTestBase::bootKernel private function Bootstraps a kernel for a test.
KernelTestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
KernelTestBase::disableModules protected function Disables modules for this test.
KernelTestBase::enableModules protected function Enables modules for this test.
KernelTestBase::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
KernelTestBase::getDatabaseConnectionInfo protected function Returns the Database connection info to be used for this test. 1
KernelTestBase::getDatabasePrefix public function
KernelTestBase::getExtensionsForModules private function Returns Extension objects for $modules to enable.
KernelTestBase::getModulesToEnable private static function Returns the modules to enable for this test.
KernelTestBase::initFileCache protected function Initializes the FileCache component.
KernelTestBase::installConfig protected function Installs default configuration for a given list of modules.
KernelTestBase::installEntitySchema protected function Installs the storage schema for a specific entity type.
KernelTestBase::installSchema protected function Installs database tables from a module schema definition.
KernelTestBase::isTestInIsolation Deprecated protected function Returns whether the current test method is running in a separate process.
KernelTestBase::prepareTemplate protected function
KernelTestBase::register public function Registers test-specific services. Overrides ServiceProviderInterface::register 26
KernelTestBase::render protected function Renders a render array. 1
KernelTestBase::setInstallProfile protected function Sets the install profile and rebuilds the container to update it.
KernelTestBase::setSetting protected function Sets an in-memory Settings variable.
KernelTestBase::setUpBeforeClass public static function 1
KernelTestBase::setUpFilesystem protected function Sets up the filesystem, so things like the file directory. 2
KernelTestBase::stop protected function Stops test execution.
KernelTestBase::tearDownCloseDatabaseConnection public function @after
KernelTestBase::vfsDump protected function Dumps the current state of the virtual filesystem to STDOUT.
KernelTestBase::__sleep public function Prevents serializing any properties.
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
RandomGeneratorTrait::$randomGenerator protected property The random generator.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers. 1
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
RandomGeneratorTrait::randomStringValidate public function Callback for random string validation.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.
StoreCreationTrait::createStore protected function Creates a store for the test.
TestRequirementsTrait::checkModuleRequirements private function Checks missing module requirements.
TestRequirementsTrait::checkRequirements protected function Check module requirements for the Drupal use case. 1
TestRequirementsTrait::getDrupalRoot protected static function Returns the Drupal root directory.
UserCreationTrait::checkPermissions protected function Checks whether a given list of permission names is valid. Aliased as: drupalCheckPermissions
UserCreationTrait::createAdminRole protected function Creates an administrative role. Aliased as: drupalCreateAdminRole
UserCreationTrait::createRole protected function Creates a role with specified permissions. Aliased as: drupalCreateRole
UserCreationTrait::createUser protected function Create a user with a given set of permissions. Aliased as: drupalCreateUser
UserCreationTrait::grantPermissions protected function Grant permissions to a user role. Aliased as: drupalGrantPermissions
UserCreationTrait::setCurrentUser protected function Switch the current logged in user. Aliased as: drupalSetCurrentUser
UserCreationTrait::setUpCurrentUser protected function Creates a random user account and sets it as current user. Aliased as: drupalSetUpCurrentUser