Shipment.php 21.8 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\commerce_shipping\Entity;

5
use Drupal\commerce_order\Entity\OrderInterface;
6
use Drupal\commerce_price\Calculator;
7
use Drupal\commerce_shipping\Plugin\Commerce\PackageType\PackageTypeInterface as PackageTypePluginInterface;
8
use Drupal\commerce_shipping\ProposedShipment;
9
use Drupal\commerce_shipping\ShipmentItem;
10
use Drupal\commerce_order\Adjustment;
11 12 13
use Drupal\commerce_price\Price;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
14 15
use Drupal\Core\Entity\EntityMalformedException;
use Drupal\Core\Entity\EntityStorageInterface;
16 17 18 19 20 21 22 23 24 25 26
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\physical\Weight;
use Drupal\profile\Entity\ProfileInterface;

/**
 * Defines the shipment entity class.
 *
 * @ContentEntityType(
 *   id = "commerce_shipment",
 *   label = @Translation("Shipment"),
27
 *   label_collection = @Translation("Shipments"),
28 29 30 31 32 33
 *   label_singular = @Translation("shipment"),
 *   label_plural = @Translation("shipments"),
 *   label_count = @PluralTranslation(
 *     singular = "@count shipment",
 *     plural = "@count shipments",
 *   ),
34
 *   bundle_label = @Translation("Shipment type"),
35
 *   handlers = {
36
 *     "list_builder" = "Drupal\commerce_shipping\ShipmentListBuilder",
37
 *     "storage" = "Drupal\commerce_shipping\ShipmentStorage",
38 39
 *     "access" = "Drupal\commerce_shipping\ShipmentAccessControlHandler",
 *     "permission_provider" = "Drupal\commerce_shipping\ShipmentPermissionProvider",
40
 *     "views_data" = "Drupal\commerce\CommerceEntityViewsData",
41 42 43 44 45
 *     "form" = {
 *       "default" = "Drupal\commerce_shipping\Form\ShipmentForm",
 *       "add" = "Drupal\commerce_shipping\Form\ShipmentForm",
 *       "edit" = "Drupal\commerce_shipping\Form\ShipmentForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
46
 *       "resend-confirmation" = "Drupal\commerce_shipping\Form\ShipmentConfirmationResendForm",
47
 *     },
48
 *     "inline_form" = "Drupal\commerce_shipping\Form\ShipmentInlineForm",
49 50 51 52
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "route_provider" = {
 *       "default" = "Drupal\commerce_shipping\ShipmentRouteProvider",
 *     },
53 54 55 56 57 58
 *   },
 *   base_table = "commerce_shipment",
 *   admin_permission = "administer commerce_shipment",
 *   fieldable = TRUE,
 *   entity_keys = {
 *     "id" = "shipment_id",
59
 *     "bundle" = "type",
60
 *     "label" = "title",
61 62
 *     "uuid" = "uuid",
 *   },
63 64 65 66 67 68 69
 *   links = {
 *     "canonical" = "/admin/commerce/orders/{commerce_order}/shipments/{commerce_shipment}",
 *     "add-page" = "/admin/commerce/orders/{commerce_order}/shipments/add",
 *     "collection" = "/admin/commerce/orders/{commerce_order}/shipments",
 *     "add-form" = "/admin/commerce/orders/{commerce_order}/shipments/add/{commerce_shipment_type}",
 *     "edit-form" = "/admin/commerce/orders/{commerce_order}/shipments/{commerce_shipment}/edit",
 *     "delete-form" = "/admin/commerce/orders/{commerce_order}/shipments/{commerce_shipment}/delete",
70
 *     "resend-confirmation-form" = "/admin/commerce/orders/{commerce_order}/shipments/{commerce_shipment}/resend-confirmation"
71
 *   },
72 73
 *   bundle_entity_type = "commerce_shipment_type",
 *   field_ui_base_route = "entity.commerce_shipment_type.edit_form",
74 75 76 77 78 79
 * )
 */
class Shipment extends ContentEntityBase implements ShipmentInterface {

  use EntityChangedTrait;

80 81 82 83 84 85 86 87 88
  /**
   * {@inheritdoc}
   */
  protected function urlRouteParameters($rel) {
    $uri_route_parameters = parent::urlRouteParameters($rel);
    $uri_route_parameters['commerce_order'] = $this->getOrderId();
    return $uri_route_parameters;
  }

89 90 91 92 93 94 95 96 97 98 99
  /**
   * {@inheritdoc}
   */
  public function clearRate() {
    $fields = ['amount', 'original_amount', 'shipping_method', 'shipping_service'];
    foreach ($fields as $field) {
      $this->set($field, NULL);
    }
    return $this;
  }

100 101 102 103
  /**
   * {@inheritdoc}
   */
  public function populateFromProposedShipment(ProposedShipment $proposed_shipment) {
104 105 106 107
    if ($proposed_shipment->getType() != $this->bundle()) {
      throw new \InvalidArgumentException(sprintf('The proposed shipment type "%s" does not match the shipment type "%s".', $proposed_shipment->getType(), $this->bundle()));
    }

108
    $this->set('order_id', $proposed_shipment->getOrderId());
109
    $this->set('title', $proposed_shipment->getTitle());
110
    $this->set('items', $proposed_shipment->getItems());
111
    $this->set('shipping_profile', $proposed_shipment->getShippingProfile());
112 113 114 115 116
    $this->set('package_type', $proposed_shipment->getPackageTypeId());
    foreach ($proposed_shipment->getCustomFields() as $field_name => $value) {
      if ($this->hasField($field_name)) {
        $this->set($field_name, $value);
      }
117 118 119
      else {
        $this->setData($field_name, $value);
      }
120
    }
121
    $this->prepareFields();
122 123
  }

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  /**
   * {@inheritdoc}
   */
  public function getOrder() {
    return $this->get('order_id')->entity;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getPackageType() {
    if (!$this->get('package_type')->isEmpty()) {
      $package_type_id = $this->get('package_type')->value;
      $package_type_manager = \Drupal::service('plugin.manager.commerce_package_type');
      return $package_type_manager->createInstance($package_type_id);
    }
  }

  /**
   * {@inheritdoc}
   */
152
  public function setPackageType(PackageTypePluginInterface $package_type) {
153
    $this->set('package_type', $package_type->getId());
154
    $this->recalculateWeight();
155 156 157 158 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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getShippingMethod() {
    return $this->get('shipping_method')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function setShippingMethod(ShippingMethodInterface $shipping_method) {
    $this->set('shipping_method', $shipping_method);
    return $this;
  }

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

  /**
   * {@inheritdoc}
   */
  public function setShippingMethodId($shipping_method_id) {
    $this->set('shipping_method', $shipping_method_id);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getShippingService() {
    return $this->get('shipping_service')->value;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getShippingProfile() {
    return $this->get('shipping_profile')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function setShippingProfile(ProfileInterface $profile) {
    $this->set('shipping_profile', $profile);
    return $this;
  }

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    return $this->get('title')->value;
  }

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

233 234 235 236 237 238 239 240 241 242 243 244
  /**
   * {@inheritdoc}
   */
  public function getItems() {
    return $this->get('items')->getShipmentItems();
  }

  /**
   * {@inheritdoc}
   */
  public function setItems(array $shipment_items) {
    $this->set('items', $shipment_items);
245
    $this->recalculateWeight();
246 247 248
    return $this;
  }

249 250 251 252 253 254 255 256 257 258 259
  /**
   * {@inheritdoc}
   */
  public function getTotalQuantity() {
    $total_quantity = '0';
    foreach ($this->getItems() as $item) {
      $total_quantity = Calculator::add($total_quantity, $item->getQuantity());
    }
    return $total_quantity;
  }

260 261 262 263 264 265 266
  /**
   * {@inheritdoc}
   */
  public function hasItems() {
    return !$this->get('items')->isEmpty();
  }

267 268 269 270 271
  /**
   * {@inheritdoc}
   */
  public function addItem(ShipmentItem $shipment_item) {
    $this->get('items')->appendItem($shipment_item);
272
    $this->recalculateWeight();
273 274 275 276 277 278 279 280
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function removeItem(ShipmentItem $shipment_item) {
    $this->get('items')->removeShipmentItem($shipment_item);
281
    $this->recalculateWeight();
282 283 284
    return $this;
  }

285 286 287 288 289 290
  /**
   * {@inheritdoc}
   */
  public function getTotalDeclaredValue() {
    $total_declared_value = NULL;
    foreach ($this->getItems() as $item) {
finne's avatar
finne committed
291
      $declared_value = $item->getDeclaredValue();
292 293 294 295 296
      $total_declared_value = $total_declared_value ? $total_declared_value->add($declared_value) : $declared_value;
    }
    return $total_declared_value;
  }

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
  /**
   * {@inheritdoc}
   */
  public function getWeight() {
    if (!$this->get('weight')->isEmpty()) {
      return $this->get('weight')->first()->toMeasurement();
    }
  }

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

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
  /**
   * {@inheritdoc}
   */
  public function getOriginalAmount() {
    if (!$this->get('original_amount')->isEmpty()) {
      return $this->get('original_amount')->first()->toPrice();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function setOriginalAmount(Price $original_amount) {
    $this->set('original_amount', $original_amount);
    return $this;
  }

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
  /**
   * {@inheritdoc}
   */
  public function getAmount() {
    if (!$this->get('amount')->isEmpty()) {
      return $this->get('amount')->first()->toPrice();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function setAmount(Price $amount) {
    $this->set('amount', $amount);
    return $this;
  }

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
  /**
   * {@inheritdoc}
   */
  public function getAdjustedAmount(array $adjustment_types = []) {
    $amount = $this->getAmount();
    if (!$amount) {
      return NULL;
    }
    foreach ($this->getAdjustments($adjustment_types) as $adjustment) {
      if (!$adjustment->isIncluded()) {
        $amount = $amount->add($adjustment->getAmount());
      }
    }
    $rounder = \Drupal::service('commerce_price.rounder');
    $amount = $rounder->round($amount);

    return $amount;
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

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

  /**
   * {@inheritdoc}
   */
  public function addAdjustment(Adjustment $adjustment) {
    $this->get('adjustments')->appendItem($adjustment);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function removeAdjustment(Adjustment $adjustment) {
    $this->get('adjustments')->removeAdjustment($adjustment);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function clearAdjustments() {
    $locked_callback = function ($adjustment) {
      /** @var \Drupal\commerce_order\Adjustment $adjustment */
      return $adjustment->isLocked();
    };
    $adjustments = array_filter($this->getAdjustments(), $locked_callback);
    $this->setAdjustments($adjustments);
    return $this;
  }

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
  /**
   * {@inheritdoc}
   */
  public function getTrackingCode() {
    return $this->get('tracking_code')->value;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getState() {
    return $this->get('state')->first();
  }

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  /**
   * {@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;
  }

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getShippedTime() {
    return $this->get('shipped')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setShippedTime($timestamp) {
    $this->set('shipped', $timestamp);
    return $this;
  }

494 495 496 497 498 499
  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);

500
    $this->prepareFields();
501
    foreach (['order_id'] as $field) {
502 503 504 505 506 507
      if ($this->get($field)->isEmpty()) {
        throw new EntityMalformedException(sprintf('Required shipment field "%s" is empty.', $field));
      }
    }
  }

508 509 510 511 512 513
  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    parent::postDelete($storage, $entities);

514 515
    /** @var \Drupal\commerce_shipping\ShippingOrderManagerInterface $shipping_order_manager */
    $shipping_order_manager = \Drupal::service('commerce_shipping.order_manager');
516 517 518 519 520 521
    // When shipments are being deleted, we need to make sure the parent order
    // is refreshed so that the corresponding shipping adjustment is removed.
    $orders_to_refresh = [];
    /** @var \Drupal\commerce_shipping\Entity\ShipmentInterface[] $entities */
    foreach ($entities as $shipment) {
      $order = $shipment->getOrder();
522
      if (empty($order) || !$shipping_order_manager->hasShipments($order)) {
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
        continue;
      }
      $order_shipments = $order->get('shipments');
      // Make sure the shipment is not being referenced by the order anymore.
      /** @var \Drupal\Core\Field\FieldItemListInterface $order_shipments */
      foreach ($order_shipments as $delta => $item) {
        if ($item->target_id == $shipment->id()) {
          $order_shipments->removeItem($delta);
        }
      }
      $orders_to_refresh[$order->id()] = $order;
    }

    foreach ($orders_to_refresh as $order) {
      $order->setRefreshState(OrderInterface::REFRESH_ON_SAVE);
      $order->save();
    }
  }

542 543 544 545 546 547 548 549 550 551 552
  /**
   * Ensures that the package_type and weight fields are populated.
   */
  protected function prepareFields() {
    if (empty($this->getPackageType()) && !empty($this->getShippingMethodId())) {
      $default_package_type = $this->getShippingMethod()->getPlugin()->getDefaultPackageType();
      $this->set('package_type', $default_package_type->getId());
    }
    $this->recalculateWeight();
  }

553 554 555 556
  /**
   * Recalculates the shipment's weight.
   */
  protected function recalculateWeight() {
557 558
    if (!$this->hasItems()) {
      // Can't calculate the weight if the items are still unavailable.
559 560 561
      return;
    }

562 563
    /** @var \Drupal\physical\Weight $weight */
    $weight = NULL;
564
    foreach ($this->getItems() as $shipment_item) {
565
      $shipment_item_weight = $shipment_item->getWeight();
566
      $weight = $weight ? $weight->add($shipment_item_weight) : $shipment_item_weight;
567 568
    }
    if ($package_type = $this->getPackageType()) {
569
      $package_type_weight = $package_type->getWeight();
570
      $weight = $weight->add($package_type_weight);
571
    }
572

573 574 575
    $this->setWeight($weight);
  }

576 577 578 579 580 581 582 583 584 585 586
  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    // The order backreference.
    $fields['order_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Order'))
      ->setDescription(t('The parent order.'))
      ->setSetting('target_type', 'commerce_order')
587
      ->setRequired(TRUE)
588 589 590 591 592 593 594 595 596 597 598 599
      ->setReadOnly(TRUE);

    $fields['package_type'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Package type'))
      ->setDescription(t('The package type.'))
      ->setRequired(TRUE)
      ->setDefaultValue('')
      ->setSetting('max_length', 255)
      ->setDisplayConfigurable('view', TRUE);

    $fields['shipping_method'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Shipping method'))
600
      ->setRequired(TRUE)
601 602 603
      ->setDescription(t('The shipping method'))
      ->setSetting('target_type', 'commerce_shipping_method')
      ->setDisplayOptions('form', [
604 605 606 607 608 609
        'type' => 'commerce_shipping_rate',
        'weight' => 0,
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'commerce_shipping_method',
610 611 612 613 614 615 616 617
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['shipping_service'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Shipping service'))
      ->setRequired(TRUE)
618
      ->setDescription(t('The shipping service.'))
619
      ->setDefaultValue('')
620
      ->setSetting('max_length', 255);
621 622

    $fields['shipping_profile'] = BaseFieldDefinition::create('entity_reference_revisions')
623
      ->setLabel(t('Shipping information'))
624
      ->setRequired(TRUE)
625 626 627 628
      ->setSetting('target_type', 'profile')
      ->setSetting('handler', 'default')
      ->setSetting('handler_settings', ['target_bundles' => ['customer']])
      ->setDisplayOptions('form', [
629
        'type' => 'commerce_shipping_profile',
630
        'weight' => -10,
631 632 633 634 635
        'settings' => [],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

636 637 638 639 640 641 642 643 644 645
    $fields['title'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Title'))
      ->setDescription(t('The shipment title.'))
      ->setRequired(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
646
        'weight' => -20,
647 648 649 650
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

651 652
    $fields['items'] = BaseFieldDefinition::create('commerce_shipment_item')
      ->setLabel(t('Items'))
653
      ->setRequired(TRUE)
654 655 656 657 658 659
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['weight'] = BaseFieldDefinition::create('physical_measurement')
      ->setLabel(t('Weight'))
660
      ->setRequired(TRUE)
661 662 663 664
      ->setSetting('measurement_type', 'weight')
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

665 666 667 668 669 670
    $fields['original_amount'] = BaseFieldDefinition::create('commerce_price')
      ->setLabel(t('Original amount'))
      ->setDescription(t('The original amount.'))
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', TRUE);

671 672
    $fields['amount'] = BaseFieldDefinition::create('commerce_price')
      ->setLabel(t('Amount'))
673
      ->setDescription(t('The amount.'))
674 675 676
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', TRUE);

677 678 679 680 681 682
    $fields['adjustments'] = BaseFieldDefinition::create('commerce_adjustment')
      ->setLabel(t('Adjustments'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', FALSE);

683 684 685 686 687 688
    $fields['tracking_code'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Tracking code'))
      ->setDescription(t('The shipment tracking code.'))
      ->setDefaultValue('')
      ->setSetting('max_length', 255)
      ->setDisplayConfigurable('form', TRUE)
689 690 691 692 693
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 50,
      ]);
694 695 696 697 698 699 700 701 702 703 704

    $fields['state'] = BaseFieldDefinition::create('state')
      ->setLabel(t('State'))
      ->setDescription(t('The shipment state.'))
      ->setRequired(TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'state_transition_form',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE)
705 706
      ->setDisplayConfigurable('view', TRUE)
      ->setSetting('workflow_callback', ['\Drupal\commerce_shipping\Entity\Shipment', 'getWorkflowId']);
707

708 709 710 711
    $fields['data'] = BaseFieldDefinition::create('map')
      ->setLabel(t('Data'))
      ->setDescription(t('A serialized array of additional data.'));

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time when the shipment was created.'))
      ->setRequired(TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time when the shipment was last updated.'))
      ->setRequired(TRUE);

    $fields['shipped'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('Shipped'))
      ->setDescription(t('The time when the shipment was shipped.'));

    return $fields;
  }

729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
  /**
   * {@inheritdoc}
   */
  public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
    $shipment_type = ShipmentType::load($bundle);
    if (!$shipment_type) {
      throw new \RuntimeException(sprintf('Could not load the "%s" shipment type.', $bundle));
    }
    $fields = [];
    $fields['shipping_profile'] = clone $base_field_definitions['shipping_profile'];
    $fields['shipping_profile']->setSetting('handler_settings', [
      'target_bundles' => [
        $shipment_type->getProfileTypeId(),
      ],
    ]);

    return $fields;
  }

748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
  /**
   * Gets the workflow ID for the state field.
   *
   * @param \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment
   *   The shipment.
   *
   * @return string
   *   The workflow ID.
   */
  public static function getWorkflowId(ShipmentInterface $shipment) {
    if (!empty($shipping_method = $shipment->get('shipping_method')->entity)) {
      if (!empty($plugin = $shipping_method->getPlugin())) {
        return $plugin->getWorkflowId();
      }
    }
    return 'shipment_default';
  }

766
}