Coupon.php 8.18 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\commerce_promotion\Entity;

5
use Drupal\commerce\Entity\CommerceContentEntityBase;
6
use Drupal\commerce_order\Entity\OrderInterface;
7
use Drupal\Core\Entity\EntityStorageInterface;
8 9 10 11 12 13 14 15 16
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Defines the Coupon entity.
 *
 * @ContentEntityType(
 *   id = "commerce_promotion_coupon",
 *   label = @Translation("Coupon"),
17 18 19 20 21 22
 *   label_singular = @Translation("coupon"),
 *   label_plural = @Translation("coupons"),
 *   label_count = @PluralTranslation(
 *     singular = "@count coupon",
 *     plural = "@count coupons",
 *   ),
23
 *   handlers = {
24
 *     "event" = "Drupal\commerce_promotion\Event\CouponEvent",
25
 *     "list_builder" = "Drupal\commerce_promotion\CouponListBuilder",
26
 *     "storage" = "Drupal\commerce_promotion\CouponStorage",
27
 *     "storage_schema" = "Drupal\commerce\CommerceContentEntityStorageSchema",
28
 *     "access" = "Drupal\commerce_promotion\CouponAccessControlHandler",
29
 *     "views_data" = "Drupal\commerce\CommerceEntityViewsData",
30
 *     "form" = {
31 32
 *       "add" = "Drupal\commerce_promotion\Form\CouponForm",
 *       "edit" = "Drupal\commerce_promotion\Form\CouponForm",
33 34
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm"
 *     },
35 36 37
 *    "local_task_provider" = {
 *       "default" = "Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
 *     },
38 39 40
 *     "route_provider" = {
 *       "default" = "Drupal\commerce_promotion\CouponRouteProvider",
 *     },
41 42
 *   },
 *   base_table = "commerce_promotion_coupon",
43
 *   admin_permission = "administer commerce_promotion",
44 45 46
 *   field_indexes = {
 *     "code"
 *   },
47 48 49 50 51 52
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "code",
 *     "uuid" = "uuid",
 *     "status" = "status",
 *   },
53 54 55 56 57 58
 *   links = {
 *     "add-form" = "/promotion/{commerce_promotion}/coupons/add",
 *     "edit-form" = "/promotion/{commerce_promotion}/coupons/{commerce_promotion_coupon}/edit",
 *     "delete-form" = "/promotion/{commerce_promotion}/coupons/{commerce_promotion_coupon}/delete",
 *     "collection" = "/promotion/{commerce_promotion}/coupons",
 *   },
59 60
 * )
 */
61
class Coupon extends CommerceContentEntityBase implements CouponInterface {
62

63 64 65 66 67 68 69 70 71
  /**
   * {@inheritdoc}
   */
  protected function urlRouteParameters($rel) {
    $uri_route_parameters = parent::urlRouteParameters($rel);
    $uri_route_parameters['commerce_promotion'] = $this->getPromotionId();
    return $uri_route_parameters;
  }

72 73 74 75
  /**
   * {@inheritdoc}
   */
  public function getPromotion() {
76
    return $this->getTranslatedReferencedEntity('promotion_id');
77 78 79 80 81 82 83 84 85
  }

  /**
   * {@inheritdoc}
   */
  public function getPromotionId() {
    return $this->get('promotion_id')->target_id;
  }

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  /**
   * {@inheritdoc}
   */
  public function getCode() {
    return $this->get('code')->value;
  }

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

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  /**
   * {@inheritdoc}
   */
  public function getUsageLimit() {
    return $this->get('usage_limit')->value;
  }

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

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  /**
   * {@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;
  }

131 132 133
  /**
   * {@inheritdoc}
   */
134
  public function isEnabled() {
135 136 137 138 139 140
    return (bool) $this->getEntityKey('status');
  }

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

146 147 148 149 150 151 152 153 154 155
  /**
   * {@inheritdoc}
   */
  public function available(OrderInterface $order) {
    if (!$this->isEnabled()) {
      return FALSE;
    }
    if (!$this->getPromotion()->available($order)) {
      return FALSE;
    }
156 157 158 159 160 161 162 163 164 165

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

166 167 168 169 170
    // Check the global usage limit fist.
    if ($usage_limit && $usage_limit <= $usage->loadByCoupon($this)) {
      return FALSE;
    }

171 172 173 174
    // Only check customer usage when email address is known.
    if ($usage_limit_customer) {
      $email = $order->getEmail();
      if ($email && $usage_limit_customer <= $usage->loadByCoupon($this, $email)) {
175 176 177
        return FALSE;
      }
    }
178 179 180 181

    return TRUE;
  }

182 183 184 185 186 187 188 189 190 191 192 193 194 195
  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);

    // Ensure there's a reference on each promotion.
    $promotion = $this->getPromotion();
    if ($promotion && !$promotion->hasCoupon($this)) {
      $promotion->addCoupon($this);
      $promotion->save();
    }
  }

196 197 198 199 200 201 202 203
  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    // Delete the related usage.
    /** @var \Drupal\commerce_promotion\PromotionUsageInterface $usage */
    $usage = \Drupal::service('commerce_promotion.usage');
    $usage->deleteByCoupon($entities);
204 205 206 207 208 209 210 211 212 213 214 215
    // Delete references to those coupons in promotions.
    foreach ($entities as $coupon) {
      $coupons_id[] = $coupon->id();
    }
    $promotions = \Drupal::entityTypeManager()->getStorage('commerce_promotion')->loadByProperties(['coupons' => $coupons_id]);
    /** @var \Drupal\commerce_promotion\Entity\PromotionInterface $promotion */
    foreach ($promotions as $promotion) {
      foreach ($entities as $entity) {
        $promotion->removeCoupon($entity);
      }
      $promotion->save();
    }
216 217
  }

218 219 220 221 222 223
  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

224 225 226 227 228 229 230 231
    // The promotion backreference, populated by Promotion::postSave().
    $fields['promotion_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Promotion'))
      ->setDescription(t('The parent promotion.'))
      ->setSetting('target_type', 'commerce_promotion')
      ->setReadOnly(TRUE)
      ->setDisplayConfigurable('view', TRUE);

232 233
    $fields['code'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Coupon code'))
234
      ->setDescription(t('The unique, machine-readable identifier for a coupon.'))
235
      ->addConstraint('CouponCode')
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
      ->setSettings([
        'max_length' => 50,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayOptions('view', [
        'label' => 'inline',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

253 254 255 256 257 258 259 260 261
    $fields['usage_limit'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Usage limit'))
      ->setDescription(t('The maximum number of times the coupon can be used. 0 for unlimited.'))
      ->setDefaultValue(0)
      ->setDisplayOptions('form', [
        'type' => 'commerce_usage_limit',
        'weight' => 4,
      ]);

262 263 264 265 266 267 268 269 270
    $fields['usage_limit_customer'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Customer usage limit'))
      ->setDescription(t('The maximum number of times the coupon can be used by a customer. 0 for unlimited.'))
      ->setDefaultValue(0)
      ->setDisplayOptions('form', [
        'type' => 'commerce_usage_limit',
        'weight' => 4,
      ]);

271
    $fields['status'] = BaseFieldDefinition::create('boolean')
272 273
      ->setLabel(t('Status'))
      ->setDescription(t('Whether the coupon is enabled.'))
274
      ->setDefaultValue(TRUE)
275 276 277 278
      ->setRequired(TRUE)
      ->setSettings([
        'on_label' => t('Enabled'),
        'off_label' => t('Disabled'),
279
      ])
280 281 282 283
      ->setDisplayOptions('form', [
        'type' => 'options_buttons',
        'weight' => 0,
      ]);
284 285 286 287 288

    return $fields;
  }

}