Promotion.php 25.2 KB
Newer Older
1 2
<?php

3
namespace Drupal\commerce_promotion\Entity;
4

5
use Drupal\commerce\ConditionGroup;
6
use Drupal\commerce\Entity\CommerceContentEntityBase;
7
use Drupal\commerce\Plugin\Commerce\Condition\ConditionInterface;
8
use Drupal\commerce\Plugin\Commerce\Condition\ParentEntityAwareInterface;
9
use Drupal\commerce_order\Entity\OrderInterface;
10
use Drupal\commerce_price\Calculator;
11
use Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\OrderItemPromotionOfferInterface;
12
use Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\PromotionOfferInterface;
13
use Drupal\Core\Datetime\DrupalDateTime;
14
use Drupal\Core\Entity\EntityStorageInterface;
15 16
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
17
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
18 19

/**
20
 * Defines the promotion entity class.
21 22
 *
 * @ContentEntityType(
23
 *   id = "commerce_promotion",
24 25 26 27
 *   label = @Translation("Promotion", context = "Commerce"),
 *   label_collection = @Translation("Promotions", context = "Commerce"),
 *   label_singular = @Translation("promotion", context = "Commerce"),
 *   label_plural = @Translation("promotions", context = "Commerce"),
28
 *   label_count = @PluralTranslation(
29 30
 *     singular = "@count promotion",
 *     plural = "@count promotions",
31
 *     context = "Commerce",
32 33
 *   ),
 *   handlers = {
34 35
 *     "event" = "Drupal\commerce_promotion\Event\PromotionEvent",
 *     "storage" = "Drupal\commerce_promotion\PromotionStorage",
36
 *     "access" = "Drupal\entity\EntityAccessControlHandler",
37
 *     "permission_provider" = "Drupal\entity\EntityPermissionProvider",
38
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
39
 *     "list_builder" = "Drupal\commerce_promotion\PromotionListBuilder",
40
 *     "views_data" = "Drupal\commerce_promotion\PromotionViewsData",
41
 *     "form" = {
42 43
 *       "default" = "Drupal\commerce_promotion\Form\PromotionForm",
 *       "add" = "Drupal\commerce_promotion\Form\PromotionForm",
44 45
 *       "enable" = "Drupal\commerce_promotion\Form\PromotionEnableForm",
 *       "disable" = "Drupal\commerce_promotion\Form\PromotionDisableForm",
46
 *       "edit" = "Drupal\commerce_promotion\Form\PromotionForm",
47
 *       "duplicate" = "Drupal\commerce_promotion\Form\PromotionForm",
48 49
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm"
 *     },
50 51 52
 *     "local_task_provider" = {
 *       "default" = "Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
 *     },
53
 *     "route_provider" = {
54
 *       "default" = "Drupal\commerce_promotion\PromotionRouteProvider",
55 56
 *       "delete-multiple" = "Drupal\entity\Routing\DeleteMultipleRouteProvider",
 *     },
57
 *     "translation" = "Drupal\commerce_promotion\PromotionTranslationHandler",
58
 *   },
59 60
 *   base_table = "commerce_promotion",
 *   data_table = "commerce_promotion_field_data",
61
 *   admin_permission = "administer commerce_promotion",
62
 *   translatable = TRUE,
63 64 65 66 67
 *   translation = {
 *     "content_translation" = {
 *       "access_callback" = "content_translation_translate_access"
 *     },
 *   },
68
 *   entity_keys = {
69
 *     "id" = "promotion_id",
70 71 72 73 74 75
 *     "label" = "name",
 *     "langcode" = "langcode",
 *     "uuid" = "uuid",
 *     "status" = "status",
 *   },
 *   links = {
76 77
 *     "add-form" = "/promotion/add",
 *     "edit-form" = "/promotion/{commerce_promotion}/edit",
78 79
 *     "enable-form" = "/promotion/{commerce_promotion}/enable",
 *     "disable-form" = "/promotion/{commerce_promotion}/disable",
80
 *     "duplicate-form" = "/promotion/{commerce_promotion}/duplicate",
81 82 83
 *     "delete-form" = "/promotion/{commerce_promotion}/delete",
 *     "delete-multiple-form" = "/admin/commerce/promotions/delete",
 *     "collection" = "/admin/commerce/promotions",
84 85 86 87
 *     "drupal:content-translation-overview" = "/promotion/{commerce_promotion}/translations",
 *     "drupal:content-translation-add" = "/promotion/{commerce_promotion}/translations/add/{source}/{target}",
 *     "drupal:content-translation-edit" = "/promotion/{commerce_promotion}/translations/edit/{language}",
 *     "drupal:content-translation-delete" = "/promotion/{commerce_promotion}/translations/delete/{language}",
88 89 90
 *   },
 * )
 */
91
class Promotion extends CommerceContentEntityBase implements PromotionInterface {
92

93 94 95 96 97 98 99 100 101 102
  /**
   * {@inheritdoc}
   */
  public function toUrl($rel = 'canonical', array $options = []) {
    if ($rel == 'canonical') {
      $rel = 'edit-form';
    }
    return parent::toUrl($rel, $options);
  }

103 104 105 106 107 108 109 110 111 112 113
  /**
   * {@inheritdoc}
   */
  public function createDuplicate() {
    $duplicate = parent::createDuplicate();
    // Coupons cannot be transferred because their codes are unique.
    $duplicate->set('coupons', []);

    return $duplicate;
  }

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }

129 130 131
  /**
   * {@inheritdoc}
   */
132 133 134 135 136 137 138 139 140 141 142 143
  public function getDisplayName() {
    return $this->get('display_name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setDisplayName($display_name) {
    $this->set('display_name', $display_name);
    return $this;
  }

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this->get('description')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setDescription($description) {
    $this->set('description', $description);
    return $this;
  }

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  /**
   * {@inheritdoc}
   */
  public function getOrderTypes() {
    return $this->get('order_types')->referencedEntities();
  }

  /**
   * {@inheritdoc}
   */
  public function setOrderTypes(array $order_types) {
    $this->set('order_types', $order_types);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOrderTypeIds() {
    $order_type_ids = [];
    foreach ($this->get('order_types') as $field_item) {
      $order_type_ids[] = $field_item->target_id;
    }
    return $order_type_ids;
  }

  /**
   * {@inheritdoc}
   */
  public function setOrderTypeIds(array $order_type_ids) {
    $this->set('order_types', $order_type_ids);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getStores() {
197
    return $this->getTranslatedReferencedEntities('stores');
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
  }

  /**
   * {@inheritdoc}
   */
  public function setStores(array $stores) {
    $this->set('stores', $stores);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getStoreIds() {
    $store_ids = [];
    foreach ($this->get('stores') as $field_item) {
      $store_ids[] = $field_item->target_id;
    }
    return $store_ids;
  }

  /**
   * {@inheritdoc}
   */
  public function setStoreIds(array $store_ids) {
    $this->set('stores', $store_ids);
    return $this;
  }

bojanz's avatar
bojanz committed
227 228 229 230 231 232 233 234 235
  /**
   * {@inheritdoc}
   */
  public function getOffer() {
    if (!$this->get('offer')->isEmpty()) {
      return $this->get('offer')->first()->getTargetInstance();
    }
  }

236 237 238 239 240 241 242 243 244 245 246
  /**
   * {@inheritdoc}
   */
  public function setOffer(PromotionOfferInterface $offer) {
    $this->set('offer', [
      'target_plugin_id' => $offer->getPluginId(),
      'target_plugin_configuration' => $offer->getConfiguration(),
    ]);
    return $this;
  }

247 248 249 250 251 252 253
  /**
   * {@inheritdoc}
   */
  public function getConditions() {
    $conditions = [];
    foreach ($this->get('conditions') as $field_item) {
      /** @var \Drupal\commerce\Plugin\Field\FieldType\PluginItemInterface $field_item */
254 255 256 257 258
      $condition = $field_item->getTargetInstance();
      if ($condition instanceof ParentEntityAwareInterface) {
        $condition->setParentEntity($this);
      }
      $conditions[] = $condition;
259 260 261 262
    }
    return $conditions;
  }

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  /**
   * {@inheritdoc}
   */
  public function setConditions(array $conditions) {
    $this->set('conditions', []);
    foreach ($conditions as $condition) {
      if ($condition instanceof ConditionInterface) {
        $this->get('conditions')->appendItem([
          'target_plugin_id' => $condition->getPluginId(),
          'target_plugin_configuration' => $condition->getConfiguration(),
        ]);
      }
    }
    return $this;
  }

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  /**
   * {@inheritdoc}
   */
  public function getConditionOperator() {
    return $this->get('condition_operator')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setConditionOperator($condition_operator) {
    $this->set('condition_operator', $condition_operator);
    return $this;
  }

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  /**
   * {@inheritdoc}
   */
  public function getCouponIds() {
    $coupon_ids = [];
    foreach ($this->get('coupons') as $field_item) {
      $coupon_ids[] = $field_item->target_id;
    }
    return $coupon_ids;
  }

  /**
   * {@inheritdoc}
   */
  public function getCoupons() {
    $coupons = $this->get('coupons')->referencedEntities();
    return $coupons;
  }

  /**
   * {@inheritdoc}
   */
  public function setCoupons(array $coupons) {
    $this->set('coupons', $coupons);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function hasCoupons() {
    return !$this->get('coupons')->isEmpty();
  }

  /**
   * {@inheritdoc}
   */
  public function addCoupon(CouponInterface $coupon) {
    if (!$this->hasCoupon($coupon)) {
      $this->get('coupons')->appendItem($coupon);
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function removeCoupon(CouponInterface $coupon) {
    $index = $this->getCouponIndex($coupon);
    if ($index !== FALSE) {
      $this->get('coupons')->offsetUnset($index);
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function hasCoupon(CouponInterface $coupon) {
    return in_array($coupon->id(), $this->getCouponIds());
  }

  /**
   * Gets the index of the given coupon.
   *
   * @param \Drupal\commerce_promotion\Entity\CouponInterface $coupon
   *   The coupon.
   *
   * @return int|bool
   *   The index of the given coupon, or FALSE if not found.
   */
  protected function getCouponIndex(CouponInterface $coupon) {
    return array_search($coupon->id(), $this->getCouponIds());
  }

369 370 371 372
  /**
   * {@inheritdoc}
   */
  public function getUsageLimit() {
373
    return $this->get('usage_limit')->value;
374 375 376 377 378 379 380 381 382 383
  }

  /**
   * {@inheritdoc}
   */
  public function setUsageLimit($usage_limit) {
    $this->set('usage_limit', $usage_limit);
    return $this;
  }

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
  /**
   * {@inheritdoc}
   */
  public function getCustomerUsageLimit() {
    return $this->get('usage_limit_customer')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCustomerUsageLimit($usage_limit_customer) {
    $this->set('usage_limit_customer', $usage_limit_customer);
    return $this;
  }

399 400 401
  /**
   * {@inheritdoc}
   */
402 403
  public function getStartDate($store_timezone = 'UTC') {
    return new DrupalDateTime($this->get('start_date')->value, $store_timezone);
404 405 406 407 408 409
  }

  /**
   * {@inheritdoc}
   */
  public function setStartDate(DrupalDateTime $start_date) {
410
    $this->get('start_date')->value = $start_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
411 412 413 414 415 416
    return $this;
  }

  /**
   * {@inheritdoc}
   */
417
  public function getEndDate($store_timezone = 'UTC') {
418
    if (!$this->get('end_date')->isEmpty()) {
419
      return new DrupalDateTime($this->get('end_date')->value, $store_timezone);
420
    }
421 422 423 424 425
  }

  /**
   * {@inheritdoc}
   */
426
  public function setEndDate(DrupalDateTime $end_date = NULL) {
427 428 429 430
    $this->get('end_date')->value = NULL;
    if ($end_date) {
      $this->get('end_date')->value = $end_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
    }
431 432
  }

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  /**
   * {@inheritdoc}
   */
  public function getCompatibility() {
    return $this->get('compatibility')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCompatibility($compatibility) {
    if (!in_array($compatibility, [self::COMPATIBLE_NONE, self::COMPATIBLE_ANY])) {
      throw new \InvalidArgumentException('Invalid compatibility type');
    }
    $this->get('compatibility')->value = $compatibility;
    return $this;
  }

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
  /**
   * {@inheritdoc}
   */
  public function isEnabled() {
    return (bool) $this->getEntityKey('status');
  }

  /**
   * {@inheritdoc}
   */
  public function setEnabled($enabled) {
    $this->set('status', (bool) $enabled);
    return $this;
  }

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  /**
   * {@inheritdoc}
   */
  public function getWeight() {
    return (int) $this->get('weight')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setWeight($weight) {
    $this->set('weight', $weight);
    return $this;
  }

481 482 483 484 485 486 487 488 489 490 491 492 493
  /**
   * {@inheritdoc}
   */
  public function available(OrderInterface $order) {
    if (!$this->isEnabled()) {
      return FALSE;
    }
    if (!in_array($order->bundle(), $this->getOrderTypeIds())) {
      return FALSE;
    }
    if (!in_array($order->getStoreId(), $this->getStoreIds())) {
      return FALSE;
    }
494
    $date = $order->getCalculationDate();
495 496
    $store_timezone = $date->getTimezone()->getName();
    $start_date = $this->getStartDate($store_timezone);
497
    if ($start_date->format('U') > $date->format('U')) {
498 499
      return FALSE;
    }
500
    $end_date = $this->getEndDate($store_timezone);
501
    if ($end_date && $end_date->format('U') <= $date->format('U')) {
502 503
      return FALSE;
    }
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522

    $usage_limit = $this->getUsageLimit();
    $usage_limit_customer = $this->getCustomerUsageLimit();
    // If there are no usage limits, the promotion is available.
    if (!$usage_limit && !$usage_limit_customer) {
      return TRUE;
    }
    /** @var \Drupal\commerce_promotion\PromotionUsageInterface $usage */
    $usage = \Drupal::service('commerce_promotion.usage');

    if ($usage_limit && $usage_limit <= $usage->load($this)) {
      return FALSE;
    }
    if ($usage_limit_customer) {
      // Promotion cannot apply to orders without email addresses.
      if (!$email = $order->getEmail()) {
        return FALSE;
      }
      if ($usage_limit_customer <= $usage->load($this, $email)) {
523 524 525 526 527 528 529
        return FALSE;
      }
    }

    return TRUE;
  }

530 531 532
  /**
   * {@inheritdoc}
   */
533
  public function applies(OrderInterface $order) {
534 535 536 537 538
    // Check compatibility.
    // @todo port remaining strategies from Commerce Discount #2762997.
    switch ($this->getCompatibility()) {
      case self::COMPATIBLE_NONE:
        // If there are any existing promotions, then this cannot apply.
539
        foreach ($order->collectAdjustments() as $adjustment) {
540 541 542 543 544 545 546 547 548 549
          if ($adjustment->getType() == 'promotion') {
            return FALSE;
          }
        }
        break;

      case self::COMPATIBLE_ANY:
        break;
    }

550 551 552
    $conditions = $this->getConditions();
    if (!$conditions) {
      // Promotions without conditions always apply.
553 554
      return TRUE;
    }
555 556 557
    // Filter the conditions just in case there are leftover order item
    // conditions (which have been moved to offer conditions).
    $conditions = array_filter($conditions, function ($condition) {
558 559 560
      /** @var \Drupal\commerce\Plugin\Commerce\Condition\ConditionInterface $condition */
      return $condition->getEntityTypeId() == 'commerce_order';
    });
561
    $condition_group = new ConditionGroup($conditions, $this->getConditionOperator());
562

563
    return $condition_group->evaluate($order);
564 565
  }

566 567 568
  /**
   * {@inheritdoc}
   */
569
  public function apply(OrderInterface $order) {
bojanz's avatar
bojanz committed
570
    $offer = $this->getOffer();
571
    if ($offer instanceof OrderItemPromotionOfferInterface) {
572
      $offer_conditions = new ConditionGroup($offer->getConditions(), $offer->getConditionOperator());
bojanz's avatar
bojanz committed
573 574
      // Apply the offer to order items that pass the conditions.
      foreach ($order->getItems() as $order_item) {
575 576 577 578
        // Skip order items with a null unit price or with a quantity = 0.
        if (!$order_item->getUnitPrice() || Calculator::compare($order_item->getQuantity(), '0') === 0) {
          continue;
        }
579
        if ($offer_conditions->evaluate($order_item)) {
bojanz's avatar
bojanz committed
580 581 582 583
          $offer->apply($order_item, $this);
        }
      }
    }
584 585 586
    else {
      $offer->apply($order, $this);
    }
587 588
  }

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
  /**
   * {@inheritdoc}
   */
  public function clear(OrderInterface $order) {
    $offer = $this->getOffer();
    if ($offer instanceof OrderItemPromotionOfferInterface) {
      foreach ($order->getItems() as $order_item) {
        $offer->clear($order_item, $this);
      }
    }
    else {
      $offer->clear($order, $this);
    }
  }

604 605 606 607 608 609 610
  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);

    // Ensure there's a back-reference on each coupon.
611
    foreach ($this->getCoupons() as $coupon) {
612 613 614 615 616 617 618 619 620 621 622
      if (!$coupon->getPromotionId()) {
        $coupon->promotion_id = $this->id();
        $coupon->save();
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
623
    // Delete the linked coupons and usage records.
624 625 626 627 628 629 630 631 632
    $coupons = [];
    foreach ($entities as $entity) {
      foreach ($entity->getCoupons() as $coupon) {
        $coupons[] = $coupon;
      }
    }
    /** @var \Drupal\commerce_promotion\CouponStorageInterface $coupon_storage */
    $coupon_storage = \Drupal::service('entity_type.manager')->getStorage('commerce_promotion_coupon');
    $coupon_storage->delete($coupons);
633 634
    /** @var \Drupal\commerce_promotion\PromotionUsageInterface $usage */
    $usage = \Drupal::service('commerce_promotion.usage');
635
    $usage->delete($entities);
636 637
  }

638 639 640 641 642 643 644 645
  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
646
      ->setDescription(t('The promotion name.'))
647 648 649 650 651 652 653 654 655 656 657
      ->setRequired(TRUE)
      ->setTranslatable(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE)
658 659
      ->setDisplayConfigurable('form', TRUE);

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
    $fields['display_name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Display name'))
      ->setDescription(t('If provided, shown on the order instead of "@translated".', [
        '@translated' => t('Discount'),
      ]))
      ->setTranslatable(TRUE)
      ->setSettings([
        'display_description' => TRUE,
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

678 679 680 681 682 683 684 685 686 687 688 689 690
    $fields['description'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Description'))
      ->setDescription(t('Additional information about the promotion to show to the customer'))
      ->setTranslatable(TRUE)
      ->setDefaultValue('')
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 1,
        'settings' => [
          'rows' => 3,
        ],
      ])
      ->setDisplayConfigurable('view', TRUE)
691 692 693 694
      ->setDisplayConfigurable('form', TRUE);

    $fields['order_types'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Order types'))
695
      ->setDescription(t('The order types for which the promotion is valid.'))
696 697 698 699 700 701 702 703 704 705 706
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_order_type')
      ->setSetting('handler', 'default')
      ->setDisplayOptions('form', [
        'type' => 'commerce_entity_select',
        'weight' => 2,
      ]);

    $fields['stores'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Stores'))
707
      ->setDescription(t('The stores for which the promotion is valid.'))
708 709 710 711 712 713 714 715 716
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_store')
      ->setSetting('handler', 'default')
      ->setDisplayOptions('form', [
        'type' => 'commerce_entity_select',
        'weight' => 2,
      ]);

717
    $fields['offer'] = BaseFieldDefinition::create('commerce_plugin_item:commerce_promotion_offer')
718
      ->setLabel(t('Offer type'))
719 720 721
      ->setCardinality(1)
      ->setRequired(TRUE)
      ->setDisplayOptions('form', [
722
        'type' => 'commerce_plugin_select',
723 724 725
        'weight' => 3,
      ]);

726
    $fields['conditions'] = BaseFieldDefinition::create('commerce_plugin_item:commerce_condition')
727 728 729 730
      ->setLabel(t('Conditions'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setRequired(FALSE)
      ->setDisplayOptions('form', [
731
        'type' => 'commerce_conditions',
732
        'weight' => 3,
733
        'settings' => [
734
          'entity_types' => ['commerce_order'],
735
        ],
736 737
      ]);

738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
    $fields['condition_operator'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Condition operator'))
      ->setDescription(t('The condition operator.'))
      ->setRequired(TRUE)
      ->setSetting('allowed_values', [
        'AND' => t('All conditions must pass'),
        'OR' => t('Only one condition must pass'),
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_buttons',
        'weight' => 4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDefaultValue('AND');

753 754 755 756
    $fields['coupons'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Coupons'))
      ->setDescription(t('Coupons which allow promotion to be redeemed.'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
757
      ->setRequired(FALSE)
758
      ->setSetting('target_type', 'commerce_promotion_coupon')
759
      ->setSetting('handler', 'default');
760

761 762
    $fields['usage_limit'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Usage limit'))
763
      ->setDescription(t('The maximum number of times the promotion can be used. 0 for unlimited.'))
764 765
      ->setDefaultValue(0)
      ->setDisplayOptions('form', [
766
        'type' => 'commerce_usage_limit',
767
        'weight' => 4,
768 769
      ]);

770 771 772 773 774 775 776 777 778
    $fields['usage_limit_customer'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Customer usage limit'))
      ->setDescription(t('The maximum number of times the promotion can be used by a customer. 0 for unlimited.'))
      ->setDefaultValue(0)
      ->setDisplayOptions('form', [
        'type' => 'commerce_usage_limit',
        'weight' => 4,
      ]);

779 780
    $fields['start_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Start date'))
781
      ->setDescription(t('The date the promotion becomes valid.'))
782
      ->setRequired(TRUE)
783
      ->setSetting('datetime_type', 'datetime')
784
      ->setDefaultValueCallback('Drupal\commerce_promotion\Entity\Promotion::getDefaultStartDate')
785
      ->setDisplayOptions('form', [
786
        'type' => 'commerce_store_datetime',
787
        'weight' => 5,
788 789 790 791
      ]);

    $fields['end_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('End date'))
792
      ->setDescription(t('The date after which the promotion is invalid.'))
793
      ->setRequired(FALSE)
794
      ->setSetting('datetime_type', 'datetime')
795
      ->setSetting('datetime_optional_label', t('Provide an end date'))
796
      ->setDisplayOptions('form', [
797
        'type' => 'commerce_store_datetime',
798
        'weight' => 6,
799 800
      ]);

801 802 803 804 805 806 807 808 809 810
    $fields['compatibility'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Compatibility with other promotions'))
      ->setSetting('allowed_values_function', ['\Drupal\commerce_promotion\Entity\Promotion', 'getCompatibilityOptions'])
      ->setRequired(TRUE)
      ->setDefaultValue(self::COMPATIBLE_ANY)
      ->setDisplayOptions('form', [
        'type' => 'options_buttons',
        'weight' => 4,
      ]);

811
    $fields['status'] = BaseFieldDefinition::create('boolean')
812
      ->setLabel(t('Status'))
813
      ->setDescription(t('Whether the promotion is enabled.'))
814
      ->setDefaultValue(TRUE)
815 816
      ->setRequired(TRUE)
      ->setSettings([
817
        'on_label' => t('Enabled'),
818 819
        'off_label' => t('Disabled'),
      ])
820
      ->setDisplayOptions('form', [
821 822
        'type' => 'options_buttons',
        'weight' => 0,
823 824
      ]);

825 826 827
    $fields['weight'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Weight'))
      ->setDescription(t('The weight of this promotion in relation to others.'))
828
      ->setDefaultValue(0);
829

830 831 832 833 834 835 836 837 838 839 840 841
    return $fields;
  }

  /**
   * Default value callback for 'start_date' base field definition.
   *
   * @see ::baseFieldDefinitions()
   *
   * @return string
   *   The default value (date string).
   */
  public static function getDefaultStartDate() {
842
    $timestamp = \Drupal::time()->getRequestTime();
843
    return gmdate(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, $timestamp);
844 845
  }

846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  /**
   * Helper callback for uasort() to sort promotions by weight and label.
   *
   * @param \Drupal\commerce_promotion\Entity\PromotionInterface $a
   *   The first promotion to sort.
   * @param \Drupal\commerce_promotion\Entity\PromotionInterface $b
   *   The second promotion to sort.
   *
   * @return int
   *   The comparison result for uasort().
   */
  public static function sort(PromotionInterface $a, PromotionInterface $b) {
    $a_weight = $a->getWeight();
    $b_weight = $b->getWeight();
    if ($a_weight == $b_weight) {
      $a_label = $a->label();
      $b_label = $b->label();
      return strnatcasecmp($a_label, $b_label);
    }
    return ($a_weight < $b_weight) ? -1 : 1;
  }

868 869 870 871 872 873 874 875 876 877 878 879 880
  /**
   * Gets the allowed values for the 'compatibility' base field.
   *
   * @return array
   *   The allowed values.
   */
  public static function getCompatibilityOptions() {
    return [
      self::COMPATIBLE_ANY => t('Any promotion'),
      self::COMPATIBLE_NONE => t('Not with any other promotions'),
    ];
  }

881
}