Currently, we don't have an "easy" way of calculating shipping rates for a shipment.
This is currently done inside the ShippingRateOptionsBuilder, which is definitely not ideal and it kind of feels weird to call that service in an API context for example.

Additionally, we currently do not allow altering the shipping rates returned, and it wouldn't make sense to fire an event from there.

I've been thinking about several different ways to improve this and first thought about introducing a calculateRates() method to shipments, but entity classes are supposed to be "dumb" and only contains minimal logic next to the getters/setters.

Instead, I'm introducing a new service called the "ShipmentManager", that currently has a single method for calculating rates, and I'm firing an events from there, for altering the rates, which would solve #2991416: Add an event for altering the calculated shipping rates.

The event for altering rates was largely copied from there, and I modified it a bit to also accept a $shipment.

Since there's currently no setter for setting the amount on the ShippingRate object, I modified the ShippingRate class and added 2 new methods:
fromArray() and toArray().

This way, when writing a subscriber, if the amount needs to be altered, it can be done using the following code:

    $rate_values = $rate->toArray();
    $rate_values['amount'] = new Price('200.00', 'USD');
    $rate = ShippingRate::fromArray($rate_values);
    $event->setRates([$rate]);

Comments

jsacksick created an issue. See original summary.

jsacksick’s picture

Status: Active » Needs review
StatusFileSize
new23.23 KB
jsacksick’s picture

StatusFileSize
new225 bytes
new23.23 KB
jsacksick’s picture

Some notes related to the patch, an event is fired for each shipping method, wondering if this has a performance impact or not.

The reason for that is that there would be no easy way to access the shipping method otherwise (There's no $shipping_rate->getShippingMethod() for instance).

bojanz’s picture

+  /**
+  * Name of the event fired after shipping rates were calculated.
+  *
+  * @Event
+  *
+  * @see \Drupal\commerce_shipping\Event\ShippingRatesPostCalculateEvent
+  */
+  const SHIPPING_RATES_POST_CALCULATE = 'commerce_shipping.rates.post_calculate';

This feels correct, but unnecessarily long. Do we lose anything by just going with const RATES = 'commerce_shipping.rates' and documenting that it's used to alter calculated rates?

@@ -106,7 +125,7 @@ class ShippingRate {
    * @return \Drupal\Core\Datetime\DrupalDateTime|null
    *   The delivery date, or NULL.
    */
-  public function getDeliveryDate() {
+  public function getDeliveryDate() : DrupalDateTime {
     return $this->deliveryDate;
   }
@@ -119,8 +138,24 @@ class ShippingRate {
    * @return string|null
    *   The delivery terms, or NULL.
    */
-  public function getDeliveryTerms() {
+  public function getDeliveryTerms() : string {
     return $this->deliveryTerms;
   }

You can't add a return typehint if NULL is a possible value, because we need to support PHP 7.0, which has no nullable typehints. In case $this->deliveryDate is NULL you will get a crash.

jsacksick’s picture

StatusFileSize
new5.84 KB
new22.47 KB
jsacksick’s picture

StatusFileSize
new646 bytes
new22.46 KB

Oops!

mglaman’s picture

So I thought return types were not allowed <= 7.1? but tests are passing?

  1. +++ b/src/ShipmentManager.php
    @@ -0,0 +1,68 @@
    +    /** @var \Drupal\commerce_shipping\ShippingMethodStorageInterface $shipping_method_storage */
    +    $shipping_method_storage = $this->entityTypeManager->getStorage('commerce_shipping_method');
    +    $shipping_methods = $shipping_method_storage->loadMultipleForShipment($shipment);
    

    Total side quest incoming: I feel like we should have a ShippingMethod repository, with loadAvailable which takes a shipment. Instead of using a storage.

  2. +++ b/src/ShipmentManager.php
    @@ -0,0 +1,68 @@
    +      // Allow the rates to be altered via code.
    +      $event = new ShippingRatesEvent($shipping_rates, $shipping_method, $shipment);
    +      $this->eventDispatcher->dispatch(ShippingEvents::SHIPPING_RATES, $event);
    +      $shipping_rates = $event->getRates();
    

    👍

  3. +++ b/src/ShippingRate.php
    @@ -67,13 +67,32 @@ class ShippingRate {
    +  public function getId() : string {
    
    @@ -86,7 +105,7 @@ class ShippingRate {
    +  public function getService() : ShippingService {
    
    @@ -96,7 +115,7 @@ class ShippingRate {
    +  public function getAmount() : Price {
    
    @@ -123,4 +142,20 @@ class ShippingRate {
    +  public function toArray() : array {
    

    Return hints require PHP7.2 :O

    Unfortunately. And Commerce is requiring 7.1 only.

  4. +++ b/src/ShippingRateOptionsBuilder.php
    @@ -46,29 +45,23 @@ class ShippingRateOptionsBuilder implements ShippingRateOptionsBuilderInterface
    -    /** @var \Drupal\commerce_shipping\ShippingMethodStorageInterface $shipping_method_storage */
    -    $shipping_method_storage = $this->entityTypeManager->getStorage('commerce_shipping_method');
    -    $shipping_methods = $shipping_method_storage->loadMultipleForShipment($shipment);
         $options = [];
    -    foreach ($shipping_methods as $shipping_method) {
    -      $shipping_method_plugin = $shipping_method->getPlugin();
    -      $shipping_rates = $shipping_method_plugin->calculateRates($shipment);
    -      foreach ($shipping_rates as $shipping_rate) {
    -        $service = $shipping_rate->getService();
    -        $amount = $shipping_rate->getAmount();
    +    $shipping_rates = $this->shipmentManager->calculateRates($shipment);
     
    -        $option_id = $shipping_method->id() . '--' . $service->getId();
    -        $option_label = $this->t('@service: @amount', [
    -          '@service' => $service->getLabel(),
    -          '@amount' => $this->currencyFormatter->format($amount->getNumber(), $amount->getCurrencyCode()),
    -        ]);
    -        $options[$option_id] = new ShippingRateOption([
    -          'id' => $option_id,
    -          'label' => $option_label,
    -          'shipping_method_id' => $shipping_method->id(),
    -          'shipping_rate' => $shipping_rate,
    -        ]);
    -      }
    

    🥳🎉

  5. +++ b/src/ShippingRateOptionsBuilder.php
    @@ -46,29 +45,23 @@ class ShippingRateOptionsBuilder implements ShippingRateOptionsBuilderInterface
    +      list($shipping_method_id, $shipping_rate_id) = explode('--', $rate_id);
    

    Isn't this data available from the rate object without having to split the rate ID? Less changes later if we deprecate the rate ID.

mglaman’s picture

jsacksick’s picture

StatusFileSize
new2.53 KB
new22.89 KB

Total side quest incoming: I feel like we should have a ShippingMethod repository, with loadAvailable which takes a shipment. Instead of using a storage.

Valid point, perhaps to threat in a separate issue?

Regarding the return hints, removing them, we also need to remove the ones added in ShippingRateOption by me :p.

Regarding #3017776: Exception in any shipping handler causes shipping to fail for all methods, wondering if we shouldn't re-roll the patch it once this gets in?

list($shipping_method_id, $shipping_rate_id) = explode('--', $rate_id);

I agree on this one, but unfortunately, the ShippingRate doesn't have access to the Shipping Method, so wondering how we should be handling this...

bojanz’s picture

Status: Needs review » Needs work

Bumping back to needs work since typehints were mistakenly removed, PHP 7.0 supports them and Commerce 2.15 has them.

I agree on this one, but unfortunately, the ShippingRate doesn't have access to the Shipping Method, so wondering how we should be handling this...

Pasting yesterday's notes on the needed solution:
#3092772: Give plugins access to the full parent config entity, not just its ID in Commerce, which gives us $this->entity in ShippingMethodBase. Have that passed to ShippingRate (most likely a BC break because we'll change __construct), so that we have $rate->getShippingMethod(). I would also make $rate->getId() return $shipping_method->id() . '--' . $service. Thus removing any need for ShippingRateOption and ShippingRateOptionsBuilder. All of this is followup material.

jsacksick’s picture

So then we're back to the patch from comment #7, anything else that needs to be added before we commit this?

bojanz’s picture

Assigned: Unassigned » bojanz

Committed #2991416: Add an event for altering the calculated shipping rates, containing relevant portions of #10.

This now needs a reroll.

jsacksick’s picture

Status: Needs work » Needs review
StatusFileSize
new12.71 KB

Attached the patch rerolled, I'm pretty sure you'd like to take care of #11 before committing it that (leaving that to you), but at least the patch applies again.

  • bojanz committed d958b0b on 8.x-2.x authored by jsacksick
    Issue #3098140 by jsacksick, bojanz, mglaman: Simplify calculating rates...
bojanz’s picture

Assigned: bojanz » Unassigned
Status: Needs review » Fixed

Committed #14.

I'm sad that we ended up abandoning the typehints we initially added to ShippingRate. Let's return to that in a followup.
#11 is also followup material cause it will be a BC break.

We now have ShippingOrderManager and ShipmentManager. Both are thin wrappers over underlying APIs, and they'll only get thinner over time (thanks to #11, for example). It might make sense in the future to admit that it's one giant facade, and unite the classes into ShippingManager. That will be up to mglaman and jacksick to decide.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.