You are here

public function PromotionOrderProcessorTest::testCouponPromotion in Commerce Core 8.2

Tests the coupon based promotion processor.

File

modules/promotion/tests/src/Kernel/PromotionOrderProcessorTest.php, line 118

Class

PromotionOrderProcessorTest
Tests the promotion order processor.

Namespace

Drupal\Tests\commerce_promotion\Kernel

Code

public function testCouponPromotion() {

  // Use addOrderItem so the total is calculated.
  $order_item = OrderItem::create([
    'type' => 'test',
    'quantity' => 2,
    'unit_price' => [
      'number' => '20.00',
      'currency_code' => 'USD',
    ],
  ]);
  $order_item
    ->save();
  $this->order
    ->addItem($order_item);
  $this->order
    ->set('state', 'draft');
  $this->order
    ->save();

  // Starts now, enabled. No end time.
  $promotion_with_coupon = Promotion::create([
    'name' => 'Promotion (with coupon)',
    'order_types' => [
      $this->order
        ->bundle(),
    ],
    'stores' => [
      $this->store
        ->id(),
    ],
    'offer' => [
      'target_plugin_id' => 'order_percentage_off',
      'target_plugin_configuration' => [
        'percentage' => '0.10',
      ],
    ],
    'conditions' => [
      [
        'target_plugin_id' => 'order_total_price',
        'target_plugin_configuration' => [
          'amount' => [
            'number' => '20.00',
            'currency_code' => 'USD',
          ],
        ],
      ],
    ],
    'start_date' => '2017-01-01',
    'status' => TRUE,
  ]);
  $promotion_with_coupon
    ->save();
  $coupon = Coupon::create([
    'code' => $this
      ->randomString(),
    'status' => TRUE,
  ]);
  $coupon
    ->save();
  $promotion_with_coupon
    ->get('coupons')
    ->appendItem($coupon);
  $promotion_with_coupon
    ->save();
  $this->container
    ->get('commerce_order.order_refresh')
    ->refresh($this->order);
  $this
    ->assertEquals(0, count($this->order
    ->getAdjustments()));
  $this->order
    ->get('coupons')
    ->appendItem($coupon);
  $this->order
    ->save();
  $this->container
    ->get('commerce_order.order_refresh')
    ->refresh($this->order);
  $this->order
    ->recalculateTotalPrice();
  $this
    ->assertEquals(1, count($this->order
    ->collectAdjustments()));
  $this
    ->assertEquals(new Price('36.00', 'USD'), $this->order
    ->getTotalPrice());
  $coupon
    ->setEnabled(FALSE);
  $coupon
    ->save();
  $this->container
    ->get('commerce_order.order_refresh')
    ->refresh($this->order);
  $this->order
    ->recalculateTotalPrice();
  $this
    ->assertEquals(0, count($this->order
    ->collectAdjustments()));
}