From 9516f8604c1fd8e6fca6d5496e6bf97df2f8b965 Mon Sep 17 00:00:00 2001
From: mglaman <mglaman@2416470.no-reply.drupal.org>
Date: Thu, 21 Jul 2016 12:33:12 -0500
Subject: [PATCH] Issue #2770747 by mglaman: Implement offer actions

---
 modules/promotion/commerce_promotion.services.yml  |  4 +
 .../promotion/src/Annotation/PromotionOffer.php    | 67 ++++++++++++++++
 modules/promotion/src/Entity/Promotion.php         | 24 ++++++
 .../promotion/src/Entity/PromotionInterface.php    |  8 ++
 .../Commerce/PromotionOffer/OrderPercentageOff.php | 29 +++++++
 .../Commerce/PromotionOffer/PercentageOffBase.php  | 62 +++++++++++++++
 .../PromotionOffer/ProductPercentageOff.php        | 29 +++++++
 .../Commerce/PromotionOffer/PromotionOfferBase.php | 91 ++++++++++++++++++++++
 .../PromotionOffer/PromotionOfferInterface.php     | 34 ++++++++
 modules/promotion/src/PromotionOfferManager.php    | 91 ++++++++++++++++++++++
 src/Element/PluginSelect.php                       |  8 +-
 src/Plugin/Field/FieldType/PluginItemDeriver.php   |  1 +
 12 files changed, 447 insertions(+), 1 deletion(-)
 create mode 100644 modules/promotion/commerce_promotion.services.yml
 create mode 100644 modules/promotion/src/Annotation/PromotionOffer.php
 create mode 100644 modules/promotion/src/Plugin/Commerce/PromotionOffer/OrderPercentageOff.php
 create mode 100644 modules/promotion/src/Plugin/Commerce/PromotionOffer/PercentageOffBase.php
 create mode 100644 modules/promotion/src/Plugin/Commerce/PromotionOffer/ProductPercentageOff.php
 create mode 100644 modules/promotion/src/Plugin/Commerce/PromotionOffer/PromotionOfferBase.php
 create mode 100644 modules/promotion/src/Plugin/Commerce/PromotionOffer/PromotionOfferInterface.php
 create mode 100644 modules/promotion/src/PromotionOfferManager.php

diff --git a/modules/promotion/commerce_promotion.services.yml b/modules/promotion/commerce_promotion.services.yml
new file mode 100644
index 0000000..36ece81
--- /dev/null
+++ b/modules/promotion/commerce_promotion.services.yml
@@ -0,0 +1,4 @@
+services:
+  plugin.manager.commerce_promotion_offer:
+    class: Drupal\commerce_promotion\PromotionOfferManager
+    parent: default_plugin_manager
diff --git a/modules/promotion/src/Annotation/PromotionOffer.php b/modules/promotion/src/Annotation/PromotionOffer.php
new file mode 100644
index 0000000..09c5b0c
--- /dev/null
+++ b/modules/promotion/src/Annotation/PromotionOffer.php
@@ -0,0 +1,67 @@
+<?php
+
+namespace Drupal\commerce_promotion\Annotation;
+
+use Drupal\Component\Annotation\Plugin;
+
+/**
+ * Defines a Promotion Offer item annotation object.
+ *
+ * Plugin namespace: Plugin\Commerce\PromotionOffer.
+ *
+ * @Annotation
+ */
+class PromotionOffer extends Plugin {
+
+
+  /**
+   * The plugin ID.
+   *
+   * @var string
+   */
+  public $id;
+
+  /**
+   * The label of the plugin.
+   *
+   * @var \Drupal\Core\Annotation\Translation
+   *
+   * @ingroup plugin_translatable
+   */
+  public $label;
+
+  /**
+   * The name of the module providing the type.
+   *
+   * @var string
+   */
+  public $module;
+
+  /**
+   * An array of context definitions describing the context used by the plugin.
+   *
+   * The array is keyed by context names.
+   *
+   * @var \Drupal\Core\Annotation\ContextDefinition[]
+   */
+  public $context = [];
+
+  /**
+   * The target this action applies to.
+   *
+   * For example, this should be 'order' or 'line_item'.
+   *
+   * @var string
+   */
+  public $target;
+
+  /**
+   * The category under which the offer should listed in the UI.
+   *
+   * @var \Drupal\Core\Annotation\Translation
+   *
+   * @ingroup plugin_translatable
+   */
+  public $category;
+
+}
diff --git a/modules/promotion/src/Entity/Promotion.php b/modules/promotion/src/Entity/Promotion.php
index ab030c3..f45e506 100644
--- a/modules/promotion/src/Entity/Promotion.php
+++ b/modules/promotion/src/Entity/Promotion.php
@@ -4,8 +4,11 @@
 
 use Drupal\Core\Datetime\DrupalDateTime;
 use Drupal\Core\Entity\ContentEntityBase;
+use Drupal\Core\Entity\EntityInterface;
 use Drupal\Core\Entity\EntityTypeInterface;
 use Drupal\Core\Field\BaseFieldDefinition;
+use Drupal\Core\Plugin\Context\Context;
+use Drupal\Core\Plugin\Context\ContextDefinition;
 
 /**
  * Defines the promotion entity class.
@@ -220,6 +223,18 @@ public function setEnabled($enabled) {
   /**
    * {@inheritdoc}
    */
+  public function apply(EntityInterface $entity) {
+    $entity_type_id = $entity->getEntityTypeId();
+    // @todo should whatever invokes this method be providing the context?
+    $context = new Context(new ContextDefinition('entity:' . $entity_type_id), $entity);
+    /** @var \Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\PromotionOfferInterface $offer */
+    $offer = $this->get('offer')->first()->getTargetInstance([$entity_type_id => $context]);
+    $offer->execute();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
   public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
     $fields = parent::baseFieldDefinitions($entity_type);
 
@@ -265,6 +280,15 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
         'weight' => 2,
       ]);
 
+    $fields['offer'] = BaseFieldDefinition::create('commerce_plugin_item:commerce_promotion_offer')
+      ->setLabel(t('Offer'))
+      ->setCardinality(1)
+      ->setRequired(TRUE)
+      ->setDisplayOptions('form', [
+        'type' => 'commerce_plugin_select',
+        'weight' => 3,
+      ]);
+
     $fields['coupons'] = BaseFieldDefinition::create('entity_reference')
       ->setLabel(t('Coupons'))
       ->setDescription(t('Coupons which allow promotion to be redeemed.'))
diff --git a/modules/promotion/src/Entity/PromotionInterface.php b/modules/promotion/src/Entity/PromotionInterface.php
index 103185a..8f9100e 100644
--- a/modules/promotion/src/Entity/PromotionInterface.php
+++ b/modules/promotion/src/Entity/PromotionInterface.php
@@ -195,4 +195,12 @@ public function isEnabled();
    */
   public function setEnabled($enabled);
 
+  /**
+   * Applies the promotion to an entity.
+   *
+   * @param \Drupal\Core\Entity\EntityInterface $entity
+   *   The entity.
+   */
+  public function apply(EntityInterface $entity);
+
 }
diff --git a/modules/promotion/src/Plugin/Commerce/PromotionOffer/OrderPercentageOff.php b/modules/promotion/src/Plugin/Commerce/PromotionOffer/OrderPercentageOff.php
new file mode 100644
index 0000000..16fdd60
--- /dev/null
+++ b/modules/promotion/src/Plugin/Commerce/PromotionOffer/OrderPercentageOff.php
@@ -0,0 +1,29 @@
+<?php
+
+namespace Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer;
+
+/**
+ * Provides a 'Order: Percentage off' condition.
+ *
+ * @PromotionOffer(
+ *   id = "commerce_promotion_order_percentage_off",
+ *   label = @Translation("Percentage off"),
+ *   target = "commerce_order",
+ * )
+ */
+class OrderPercentageOff extends PercentageOffBase {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function execute() {
+    if ($this->configuration['amount'] != 0) {
+      /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
+      $order = $this->getTargetEntity();
+
+      // @todo we have no way to apply currently..
+      $calculated_amount = $order->total_price->amount * $this->getAmount();
+    }
+  }
+
+}
diff --git a/modules/promotion/src/Plugin/Commerce/PromotionOffer/PercentageOffBase.php b/modules/promotion/src/Plugin/Commerce/PromotionOffer/PercentageOffBase.php
new file mode 100644
index 0000000..ce57a5d
--- /dev/null
+++ b/modules/promotion/src/Plugin/Commerce/PromotionOffer/PercentageOffBase.php
@@ -0,0 +1,62 @@
+<?php
+
+namespace Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer;
+
+use Drupal\Core\Form\FormStateInterface;
+
+/**
+ * Provides base class for percentage off offers.
+ */
+abstract class PercentageOffBase extends PromotionOfferBase {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function defaultConfiguration() {
+    return [
+      'amount' => 0,
+    ] + parent::defaultConfiguration();
+  }
+
+  /**
+   * Gets the percentage amount, as a decimal.
+   *
+   * @return float
+   *   The amount.
+   */
+  public function getAmount() {
+    return $this->configuration['amount'];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
+    $form += parent::buildConfigurationForm($form, $form_state);
+
+    $form['amount'] = [
+      '#type' => 'number',
+      '#title' => $this->t('Percentage'),
+      '#default_value' => $this->configuration['amount'] * 100,
+      '#maxlength' => 255,
+      '#required' => TRUE,
+      '#step' => 0.1,
+      '#min' => 0,
+      '#max' => 100,
+      '#length' => 4,
+      '#field_suffix' => t('%'),
+    ];
+
+    return $form;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
+    $values = $form_state->getValue($form['#parents']);
+    $this->configuration['amount'] = ($values['amount'] / 100);
+    parent::submitConfigurationForm($form, $form_state);
+  }
+
+}
diff --git a/modules/promotion/src/Plugin/Commerce/PromotionOffer/ProductPercentageOff.php b/modules/promotion/src/Plugin/Commerce/PromotionOffer/ProductPercentageOff.php
new file mode 100644
index 0000000..ba3982b
--- /dev/null
+++ b/modules/promotion/src/Plugin/Commerce/PromotionOffer/ProductPercentageOff.php
@@ -0,0 +1,29 @@
+<?php
+
+namespace Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer;
+
+/**
+ * Provides a 'Product: Percentage off' condition.
+ *
+ * @PromotionOffer(
+ *   id = "commerce_promotion_product_percentage_off",
+ *   label = @Translation("Percentage off"),
+ *   target = "commerce_line_item",
+ * )
+ */
+class ProductPercentageOff extends PercentageOffBase {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function execute() {
+    if ($this->configuration['amount'] != 0) {
+      /** @var \Drupal\commerce_order\Entity\LineItemInterface $line_item */
+      $line_item = $this->getTargetEntity();
+
+      // @todo we have no way to apply currently..
+      $calculated_amount = $line_item->getTotalPrice()->getDecimalAmount() * $this->getAmount();
+    }
+  }
+
+}
diff --git a/modules/promotion/src/Plugin/Commerce/PromotionOffer/PromotionOfferBase.php b/modules/promotion/src/Plugin/Commerce/PromotionOffer/PromotionOfferBase.php
new file mode 100644
index 0000000..360083a
--- /dev/null
+++ b/modules/promotion/src/Plugin/Commerce/PromotionOffer/PromotionOfferBase.php
@@ -0,0 +1,91 @@
+<?php
+
+namespace Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer;
+
+use Drupal\Core\Executable\ExecutablePluginBase;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Plugin\ContextAwarePluginAssignmentTrait;
+
+/**
+ * Base class for Promotion Offer plugins.
+ */
+abstract class PromotionOfferBase extends ExecutablePluginBase implements PromotionOfferInterface {
+
+  use ContextAwarePluginAssignmentTrait;
+
+  /**
+   * {@inheritdoc}
+   */
+  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
+    parent::__construct($configuration, $plugin_id, $plugin_definition);
+
+    $this->setConfiguration($configuration);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function appliesTo() {
+    return $this->configuration['target'];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTargetEntity() {
+    return $this->getContextValue($this->appliesTo());
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
+    $contexts = $form_state->getTemporaryValue('gathered_contexts') ?: [];
+    $form['context_mapping'] = $this->addContextAssignmentElement($this, $contexts);
+    return $form;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function calculateDependencies() {
+    return [];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function defaultConfiguration() {
+    return [];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getConfiguration() {
+    return [
+      'id' => $this->getPluginId(),
+    ] + $this->configuration;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function setConfiguration(array $configuration) {
+    $this->configuration = $configuration + $this->defaultConfiguration();
+    return $this;
+  }
+
+}
diff --git a/modules/promotion/src/Plugin/Commerce/PromotionOffer/PromotionOfferInterface.php b/modules/promotion/src/Plugin/Commerce/PromotionOffer/PromotionOfferInterface.php
new file mode 100644
index 0000000..d443320
--- /dev/null
+++ b/modules/promotion/src/Plugin/Commerce/PromotionOffer/PromotionOfferInterface.php
@@ -0,0 +1,34 @@
+<?php
+
+namespace Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer;
+
+use Drupal\Component\Plugin\ConfigurablePluginInterface;
+use Drupal\Component\Plugin\PluginInspectionInterface;
+use Drupal\Core\Executable\ExecutableInterface;
+use Drupal\Core\Plugin\PluginFormInterface;
+
+/**
+ * Defines an interface for Offer plugins.
+ */
+interface PromotionOfferInterface extends ExecutableInterface, PluginFormInterface, ConfigurablePluginInterface, PluginInspectionInterface {
+
+  const ORDER = 'commerce_order';
+  const LINE_ITEM = 'commerce_line_item';
+
+  /**
+   * Returns what entity the promotion offer applies to.
+   *
+   * @return string
+   *   The entity type it applies to.
+   */
+  public function appliesTo();
+
+  /**
+   * Get the target entity for the offer.
+   *
+   * @return \Drupal\Core\Entity\EntityInterface
+   *   The target entity.
+   */
+  public function getTargetEntity();
+
+}
diff --git a/modules/promotion/src/PromotionOfferManager.php b/modules/promotion/src/PromotionOfferManager.php
new file mode 100644
index 0000000..19201a2
--- /dev/null
+++ b/modules/promotion/src/PromotionOfferManager.php
@@ -0,0 +1,91 @@
+<?php
+
+namespace Drupal\commerce_promotion;
+
+use Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\PromotionOfferInterface;
+use Drupal\Component\Plugin\CategorizingPluginManagerInterface;
+use Drupal\Component\Plugin\Exception\PluginException;
+use Drupal\Core\Plugin\CategorizingPluginManagerTrait;
+use Drupal\Core\Plugin\Context\ContextDefinition;
+use Drupal\Core\Plugin\DefaultPluginManager;
+use Drupal\Core\Cache\CacheBackendInterface;
+use Drupal\Core\Extension\ModuleHandlerInterface;
+
+/**
+ * Provides the Offer plugin manager.
+ */
+class PromotionOfferManager extends DefaultPluginManager implements CategorizingPluginManagerInterface {
+
+  use CategorizingPluginManagerTrait;
+
+  /**
+   * Constructor for OfferManager objects.
+   *
+   * @param \Traversable $namespaces
+   *   An object that implements \Traversable which contains the root paths
+   *   keyed by the corresponding namespace to look for plugin implementations.
+   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
+   *   Cache backend instance to use.
+   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
+   *   The module handler to invoke the alter hook with.
+   */
+  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
+    parent::__construct('Plugin/Commerce/PromotionOffer', $namespaces, $module_handler, 'Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\PromotionOfferInterface', 'Drupal\commerce_promotion\Annotation\PromotionOffer');
+
+    $this->alterInfo('commerce_promotion_offer_info');
+    $this->setCacheBackend($cache_backend, 'commerce_promotion_offer_plugins');
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function createInstance($plugin_id, array $configuration = []) {
+    $plugin = $this->getFactory()->createInstance($plugin_id, $configuration);
+
+    // If we receive any context values via config set it into the plugin.
+    if (!empty($configuration['context'])) {
+      foreach ($configuration['context'] as $name => $context) {
+        $plugin->setContextValue($name, $context);
+      }
+    }
+
+    return $plugin;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function processDefinition(&$definition, $plugin_id) {
+    parent::processDefinition($definition, $plugin_id);
+
+    foreach (['id', 'label', 'target'] as $required_property) {
+      if (empty($definition[$required_property])) {
+        throw new PluginException(sprintf('The promotion offer %s must define the %s property.', $plugin_id, $required_property));
+      }
+    }
+
+    $target = $definition['target'];
+    if (!\Drupal::entityTypeManager()->getDefinition($target)) {
+      throw new PluginException(sprintf('The promotion offer %s must reference a valid entity type, %s given.', $plugin_id, $target));
+    }
+
+    // If the plugin did not specify a category, process that.
+    if (empty($definition['category'])) {
+      if ($target == PromotionOfferInterface::ORDER) {
+        $definition['category'] = $this->t('Order');
+      }
+      elseif ($target == PromotionOfferInterface::LINE_ITEM) {
+        $definition['category'] = $this->t('Product');
+      }
+      else {
+        $definition['category'] = $this->t('Other');
+      }
+    }
+
+    // Generate the context definition if it is missing.
+    if (empty($definition['context'][$target])) {
+      $definition['context'][$target] = new ContextDefinition('entity:' . $target, $definition['category']);
+    }
+  }
+
+}
diff --git a/src/Element/PluginSelect.php b/src/Element/PluginSelect.php
index f9df6e1..864850d 100644
--- a/src/Element/PluginSelect.php
+++ b/src/Element/PluginSelect.php
@@ -107,7 +107,13 @@ public static function processPluginSelect(&$element, FormStateInterface $form_s
         continue;
       }
 
-      $element['target_plugin_id']['#options'][$definition['id']] = $definition['label'];
+      // Group categorized plugins.
+      if (isset($definition['category'])) {
+        $element['target_plugin_id']['#options'][(string) $definition['category']][$definition['id']] = $definition['label'];
+      }
+      else {
+        $element['target_plugin_id']['#options'][$definition['id']] = $definition['label'];
+      }
     }
 
     if ($target_plugin_id != '_none') {
diff --git a/src/Plugin/Field/FieldType/PluginItemDeriver.php b/src/Plugin/Field/FieldType/PluginItemDeriver.php
index 3b51531..91716b7 100644
--- a/src/Plugin/Field/FieldType/PluginItemDeriver.php
+++ b/src/Plugin/Field/FieldType/PluginItemDeriver.php
@@ -18,6 +18,7 @@ public function getDerivativeDefinitions($base_plugin_definition) {
     $supported = [
       'condition' => $this->t('Conditions'),
       'action' => $this->t('Action'),
+      'commerce_promotion_offer' => $this->t('Promotion Offer'),
     ];
 
     foreach ($supported as $id => $label) {
