OrderItem.php 15.5 KB
Newer Older
dwkitchen's avatar
dwkitchen committed
1 2
<?php

3
namespace Drupal\commerce_order\Entity;
dwkitchen's avatar
dwkitchen committed
4

5
use Drupal\commerce\Entity\CommerceContentEntityBase;
6
use Drupal\commerce_order\Adjustment;
7
use Drupal\commerce_price\Price;
8
use Drupal\Core\Entity\EntityChangedTrait;
dwkitchen's avatar
dwkitchen committed
9 10
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
11
use Drupal\Core\Field\BaseFieldDefinition;
dwkitchen's avatar
dwkitchen committed
12 13

/**
14
 * Defines the order item entity class.
dwkitchen's avatar
dwkitchen committed
15 16
 *
 * @ContentEntityType(
17
 *   id = "commerce_order_item",
18
 *   label = @Translation("Order item"),
19 20
 *   label_singular = @Translation("order item"),
 *   label_plural = @Translation("order items"),
21
 *   label_count = @PluralTranslation(
22 23
 *     singular = "@count order item",
 *     plural = "@count order items",
24
 *   ),
bojanz's avatar
bojanz committed
25
 *   bundle_label = @Translation("Order item type"),
dwkitchen's avatar
dwkitchen committed
26
 *   handlers = {
27 28
 *     "event" = "Drupal\commerce_order\Event\OrderItemEvent",
 *     "storage" = "Drupal\commerce_order\OrderItemStorage",
bojanz's avatar
bojanz committed
29 30
 *     "access" = "Drupal\commerce_order\OrderItemAccessControlHandler",
 *     "permission_provider" = "Drupal\commerce_order\OrderItemPermissionProvider",
31
 *     "views_data" = "Drupal\commerce_order\OrderItemViewsData",
dwkitchen's avatar
dwkitchen committed
32
 *     "form" = {
33
 *       "default" = "Drupal\Core\Entity\ContentEntityForm",
34
 *     },
35
 *     "inline_form" = "Drupal\commerce_order\Form\OrderItemInlineForm",
dwkitchen's avatar
dwkitchen committed
36
 *   },
37
 *   base_table = "commerce_order_item",
38
 *   admin_permission = "administer commerce_order",
dwkitchen's avatar
dwkitchen committed
39
 *   entity_keys = {
40
 *     "id" = "order_item_id",
dwkitchen's avatar
dwkitchen committed
41
 *     "uuid" = "uuid",
bojanz's avatar
bojanz committed
42 43
 *     "bundle" = "type",
 *     "label" = "title",
dwkitchen's avatar
dwkitchen committed
44
 *   },
45 46
 *   bundle_entity_type = "commerce_order_item_type",
 *   field_ui_base_route = "entity.commerce_order_item_type.edit_form",
dwkitchen's avatar
dwkitchen committed
47 48
 * )
 */
49
class OrderItem extends CommerceContentEntityBase implements OrderItemInterface {
dwkitchen's avatar
dwkitchen committed
50

bojanz's avatar
bojanz committed
51
  use EntityChangedTrait;
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66
  /**
   * {@inheritdoc}
   */
  public function getOrder() {
    return $this->get('order_id')->entity;
  }

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

67 68 69 70 71 72 73
  /**
   * {@inheritdoc}
   */
  public function hasPurchasedEntity() {
    return !$this->get('purchased_entity')->isEmpty();
  }

74 75 76 77
  /**
   * {@inheritdoc}
   */
  public function getPurchasedEntity() {
78
    return $this->getTranslatedReferencedEntity('purchased_entity');
79 80 81 82 83 84 85 86 87
  }

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

bojanz's avatar
bojanz committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    return $this->get('title')->value;
  }

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

103 104 105 106
  /**
   * {@inheritdoc}
   */
  public function getQuantity() {
107
    return (string) $this->get('quantity')->value;
108 109 110 111 112 113
  }

  /**
   * {@inheritdoc}
   */
  public function setQuantity($quantity) {
114
    $this->set('quantity', (string) $quantity);
115
    $this->recalculateTotalPrice();
116 117 118
    return $this;
  }

119 120 121 122
  /**
   * {@inheritdoc}
   */
  public function getUnitPrice() {
123 124 125
    if (!$this->get('unit_price')->isEmpty()) {
      return $this->get('unit_price')->first()->toPrice();
    }
126 127
  }

128 129 130
  /**
   * {@inheritdoc}
   */
131
  public function setUnitPrice(Price $unit_price, $override = FALSE) {
132
    $this->set('unit_price', $unit_price);
133
    $this->set('overridden_unit_price', $override);
134 135 136 137
    $this->recalculateTotalPrice();
    return $this;
  }

138 139 140 141
  /**
   * {@inheritdoc}
   */
  public function isUnitPriceOverridden() {
142
    return (bool) $this->get('overridden_unit_price')->value;
143 144
  }

145 146 147
  /**
   * {@inheritdoc}
   */
148 149 150
  public function getTotalPrice() {
    if (!$this->get('total_price')->isEmpty()) {
      return $this->get('total_price')->first()->toPrice();
151 152 153
    }
  }

154 155 156
  /**
   * {@inheritdoc}
   */
157 158 159 160 161 162 163 164 165 166 167 168 169 170
  public function getAdjustments(array $adjustment_types = []) {
    /** @var \Drupal\commerce_order\Adjustment[] $adjustments */
    $adjustments = $this->get('adjustments')->getAdjustments();
    // Filter adjustments by type, if needed.
    if ($adjustment_types) {
      foreach ($adjustments as $index => $adjustment) {
        if (!in_array($adjustment->getType(), $adjustment_types)) {
          unset($adjustments[$index]);
        }
      }
      $adjustments = array_values($adjustments);
    }

    return $adjustments;
dwkitchen's avatar
dwkitchen committed
171 172 173 174 175
  }

  /**
   * {@inheritdoc}
   */
176 177
  public function setAdjustments(array $adjustments) {
    $this->set('adjustments', $adjustments);
dwkitchen's avatar
dwkitchen committed
178 179 180 181 182 183
    return $this;
  }

  /**
   * {@inheritdoc}
   */
184 185
  public function addAdjustment(Adjustment $adjustment) {
    $this->get('adjustments')->appendItem($adjustment);
186 187 188
    if ($this->getOrder()) {
      $this->getOrder()->recalculateTotalPrice();
    }
dwkitchen's avatar
dwkitchen committed
189 190 191
    return $this;
  }

192 193 194
  /**
   * {@inheritdoc}
   */
195 196
  public function removeAdjustment(Adjustment $adjustment) {
    $this->get('adjustments')->removeAdjustment($adjustment);
197 198 199
    if ($this->getOrder()) {
      $this->getOrder()->recalculateTotalPrice();
    }
200
    return $this;
201 202 203 204 205
  }

  /**
   * {@inheritdoc}
   */
206
  public function usesLegacyAdjustments() {
207
    return (bool) $this->get('uses_legacy_adjustments')->value;
208 209
  }

210 211 212
  /**
   * {@inheritdoc}
   */
213
  public function getAdjustedTotalPrice(array $adjustment_types = []) {
214 215 216 217 218 219 220
    $total_price = $this->getTotalPrice();
    if (!$total_price) {
      return NULL;
    }

    if ($this->usesLegacyAdjustments()) {
      $adjusted_unit_price = $this->getAdjustedUnitPrice($adjustment_types);
221 222
      $adjusted_total_price = $adjusted_unit_price->multiply($this->getQuantity());
    }
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    else {
      $adjusted_total_price = $this->applyAdjustments($total_price, $adjustment_types);
    }

    $rounder = \Drupal::service('commerce_price.rounder');
    $adjusted_total_price = $rounder->round($adjusted_total_price);

    return $adjusted_total_price;
  }

  /**
   * {@inheritdoc}
   */
  public function getAdjustedUnitPrice(array $adjustment_types = []) {
    $unit_price = $this->getUnitPrice();
    if (!$unit_price) {
      return NULL;
    }

    if ($this->usesLegacyAdjustments()) {
      $adjusted_unit_price = $this->applyAdjustments($unit_price, $adjustment_types);
    }
    else {
      $adjusted_total_price = $this->getAdjustedTotalPrice($adjustment_types);
      $adjusted_unit_price = $adjusted_total_price->divide($this->getQuantity());
    }

    $rounder = \Drupal::service('commerce_price.rounder');
    $adjusted_unit_price = $rounder->round($adjusted_unit_price);

    return $adjusted_unit_price;
  }

  /**
   * Applies adjustments to the given price.
   *
   * @param \Drupal\commerce_price\Price $price
   *   The price.
   * @param string[] $adjustment_types
   *   The adjustment types to include in the adjusted price.
   *   Examples: fee, promotion, tax. Defaults to all adjustment types.
   *
   * @return \Drupal\commerce_price\Price
   *   The adjusted price.
   */
  protected function applyAdjustments(Price $price, array $adjustment_types = []) {
    $adjusted_price = $price;
270 271 272
    foreach ($this->getAdjustments($adjustment_types) as $adjustment) {
      if (!$adjustment->isIncluded()) {
        $adjusted_price = $adjusted_price->add($adjustment->getAmount());
273 274 275
      }
    }
    return $adjusted_price;
276 277
  }

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
  /**
   * {@inheritdoc}
   */
  public function getData($key, $default = NULL) {
    $data = [];
    if (!$this->get('data')->isEmpty()) {
      $data = $this->get('data')->first()->getValue();
    }
    return isset($data[$key]) ? $data[$key] : $default;
  }

  /**
   * {@inheritdoc}
   */
  public function setData($key, $value) {
    $this->get('data')->__set($key, $value);
    return $this;
  }

297 298 299 300 301 302 303 304 305 306 307 308
  /**
   * {@inheritdoc}
   */
  public function unsetData($key) {
    if (!$this->get('data')->isEmpty()) {
      $data = $this->get('data')->first()->getValue();
      unset($data[$key]);
      $this->set('data', $data);
    }
    return $this;
  }

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
  /**
   * {@inheritdoc}
   */
  public function isLocked() {
    return (bool) $this->get('locked')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function lock() {
    $this->set('locked', TRUE);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function unlock() {
    $this->set('locked', FALSE);
    return $this;
  }

332 333 334
  /**
   * {@inheritdoc}
   */
335 336
  public function getCreatedTime() {
    return $this->get('created')->value;
337 338 339 340 341
  }

  /**
   * {@inheritdoc}
   */
342 343
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
344 345 346
    return $this;
  }

347 348 349 350 351
  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);
352 353
    $this->recalculateTotalPrice();
  }
354

355
  /**
356
   * Recalculates the order item total price.
357 358
   */
  protected function recalculateTotalPrice() {
359
    if ($unit_price = $this->getUnitPrice()) {
360 361 362
      $rounder = \Drupal::service('commerce_price.rounder');
      $total_price = $unit_price->multiply($this->getQuantity());
      $this->total_price = $rounder->round($total_price);
363
    }
364 365
  }

dwkitchen's avatar
dwkitchen committed
366 367 368
  /**
   * {@inheritdoc}
   */
369
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
bojanz's avatar
bojanz committed
370
    $fields = parent::baseFieldDefinitions($entity_type);
dwkitchen's avatar
dwkitchen committed
371

372 373 374 375 376 377 378
    // The order backreference, populated by Order::postSave().
    $fields['order_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Order'))
      ->setDescription(t('The parent order.'))
      ->setSetting('target_type', 'commerce_order')
      ->setReadOnly(TRUE);

379 380
    $fields['purchased_entity'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Purchased entity'))
381
      ->setDescription(t('The purchased entity.'))
382
      ->setRequired(TRUE)
383
      ->addConstraint('PurchasedEntityAvailable')
384 385 386 387 388 389 390 391 392
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => -1,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'placeholder' => '',
        ],
      ])
393 394 395
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

396 397 398 399 400 401 402
    /** @var \Drupal\commerce\PurchasableEntityTypeRepositoryInterface $purchasable_entity_type_repository */
    $purchasable_entity_type_repository = \Drupal::service('commerce.purchasable_entity_type_repository');
    $default_purchasable_entity_type = $purchasable_entity_type_repository->getDefaultPurchasableEntityType();
    if ($default_purchasable_entity_type) {
      $fields['purchased_entity']->setSetting('target_type', $default_purchasable_entity_type->id());
    }

bojanz's avatar
bojanz committed
403 404
    $fields['title'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Title'))
405
      ->setDescription(t('The order item title.'))
bojanz's avatar
bojanz committed
406 407 408 409 410
      ->setSettings([
        'default_value' => '',
        'max_length' => 512,
      ]);

411 412
    $fields['quantity'] = BaseFieldDefinition::create('decimal')
      ->setLabel(t('Quantity'))
413
      ->setDescription(t('The number of purchased units.'))
414 415
      ->setReadOnly(TRUE)
      ->setSetting('unsigned', TRUE)
416
      ->setSetting('min', 0)
417
      ->setDefaultValue(1)
418
      ->setDisplayOptions('form', [
419
        'type' => 'commerce_quantity',
420
        'weight' => 1,
421
      ])
422 423 424
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

425
    $fields['unit_price'] = BaseFieldDefinition::create('commerce_price')
426 427
      ->setLabel(t('Unit price'))
      ->setDescription(t('The price of a single unit.'))
428
      ->setRequired(TRUE)
429
      ->setDisplayOptions('form', [
430
        'type' => 'commerce_unit_price',
431
        'weight' => 2,
432 433 434
        'settings' => [
          'require_confirmation' => TRUE,
        ],
435
      ])
436 437 438
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

439 440 441 442 443
    $fields['overridden_unit_price'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Overridden unit price'))
      ->setDescription(t('Whether the unit price is overridden.'))
      ->setDefaultValue(FALSE);

444 445 446 447 448 449 450
    $fields['total_price'] = BaseFieldDefinition::create('commerce_price')
      ->setLabel(t('Total price'))
      ->setDescription(t('The total price of the order item.'))
      ->setReadOnly(TRUE)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', TRUE);

451 452 453 454 455 456 457
    $fields['adjustments'] = BaseFieldDefinition::create('commerce_adjustment')
      ->setLabel(t('Adjustments'))
      ->setRequired(FALSE)
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', TRUE);

458 459 460 461 462 463 464
    $fields['uses_legacy_adjustments'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Uses legacy adjustments'))
      ->setSettings([
        'on_label' => t('Yes'),
        'off_label' => t('No'),
      ])
      ->setDefaultValue(FALSE);
dwkitchen's avatar
dwkitchen committed
465

466 467 468 469
    $fields['data'] = BaseFieldDefinition::create('map')
      ->setLabel(t('Data'))
      ->setDescription(t('A serialized array of additional data.'));

470 471 472 473 474 475 476 477
    $fields['locked'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Locked'))
      ->setSettings([
        'on_label' => t('Yes'),
        'off_label' => t('No'),
      ])
      ->setDefaultValue(FALSE);

478 479
    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
480
      ->setDescription(t('The time when the order item was created.'))
481 482 483 484 485 486
      ->setRequired(TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'timestamp',
        'weight' => 0,
      ])
487 488
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
489 490 491

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
492
      ->setDescription(t('The time when the order item was last edited.'))
493 494
      ->setRequired(TRUE);

dwkitchen's avatar
dwkitchen committed
495 496 497
    return $fields;
  }

498 499 500
  /**
   * {@inheritdoc}
   */
501
  public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
502 503
    /** @var \Drupal\commerce_order\Entity\OrderItemTypeInterface $order_item_type */
    $order_item_type = OrderItemType::load($bundle);
504 505 506
    if (!$order_item_type) {
      throw new \RuntimeException(sprintf('Could not load the "%s" order item type.', $bundle));
    }
507
    $purchasable_entity_type = $order_item_type->getPurchasableEntityTypeId();
508

509
    $fields = [];
510 511 512
    $fields['purchased_entity'] = clone $base_field_definitions['purchased_entity'];
    if ($purchasable_entity_type) {
      $fields['purchased_entity']->setSetting('target_type', $purchasable_entity_type);
513 514
    }
    else {
515
      // This order item type won't reference a purchasable entity. The field
516
      // can't be removed here, or converted to a configurable one, so it's
517
      // hidden instead. https://www.drupal.org/node/2346347#comment-10254087.
518 519
      $fields['purchased_entity']->setRequired(FALSE);
      $fields['purchased_entity']->setDisplayOptions('form', [
520
        'region' => 'hidden',
521 522 523 524 525
      ]);
      $fields['purchased_entity']->setDisplayConfigurable('form', FALSE);
      $fields['purchased_entity']->setDisplayConfigurable('view', FALSE);
      $fields['purchased_entity']->setReadOnly(TRUE);

bojanz's avatar
bojanz committed
526
      // Make the title field visible and required.
527
      $fields['title'] = clone $base_field_definitions['title'];
bojanz's avatar
bojanz committed
528 529
      $fields['title']->setRequired(TRUE);
      $fields['title']->setDisplayOptions('form', [
530 531 532
        'type' => 'string_textfield',
        'weight' => -1,
      ]);
bojanz's avatar
bojanz committed
533 534
      $fields['title']->setDisplayConfigurable('form', TRUE);
      $fields['title']->setDisplayConfigurable('view', TRUE);
535 536 537 538 539 540 541 542 543 544

      // The unit price is always an override when there's no purchased entity.
      $fields['unit_price'] = clone $base_field_definitions['unit_price'];
      $fields['unit_price']->setDisplayOptions('form', [
        'type' => 'commerce_unit_price',
        'weight' => 2,
        'settings' => [
          'require_confirmation' => FALSE,
        ],
      ]);
545 546 547 548 549
    }

    return $fields;
  }

dwkitchen's avatar
dwkitchen committed
550
}