-
-
Save jsacksick/fde031197df92236ef5a916775e17a2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
namespace Drupal\my_module\OrderProcessor; | |
use Drupal\commerce_order\Entity\OrderInterface; | |
use Drupal\commerce_order\OrderProcessorInterface; | |
use Drupal\commerce_shipping\ShipmentManagerInterface; | |
use Drupal\commerce_shipping\ShippingOrderManagerInterface; | |
use Drupal\profile\Entity\Profile; | |
/** | |
* Ensures there are shipments from the start. | |
*/ | |
final class ShippingProcessor implements OrderProcessorInterface { | |
/** | |
* The shipping order manager. | |
* | |
* @var \Drupal\commerce_shipping\ShippingOrderManagerInterface | |
*/ | |
protected $shippingOrderManager; | |
/** | |
* The shipment manager. | |
* | |
* @var \Drupal\commerce_shipping\ShipmentManagerInterface | |
*/ | |
protected $shipmentManager; | |
public function __construct(ShippingOrderManagerInterface $shippingOrderManager, ShipmentManagerInterface $shipmentManager) { | |
$this->shippingOrderManager = $shippingOrderManager; | |
$this->shipmentManager = $shipmentManager; | |
} | |
public function process(OrderInterface $order) { | |
if ($order->isNew() || $this->shippingOrderManager->hasShipments($order)) { | |
return; | |
} | |
$collected_profiles = $order->collectProfiles(); | |
$shipping_profile = $collected_profiles['shipping'] ?? NULL; | |
// @todo remove and force specifying a zip code. | |
if ($shipping_profile === NULL) { | |
$shipping_profile = Profile::create([ | |
'type' => 'customer', | |
'uid' => 0, | |
]); | |
} | |
$shipments = $this->shippingOrderManager->pack($order, $shipping_profile); | |
foreach ($shipments as $shipment) { | |
$rates = $this->shipmentManager->calculateRates($shipment); | |
if (count($rates) > 0 ) { | |
$rate = $this->shipmentManager->selectDefaultRate($shipment, $rates); | |
$this->shipmentManager->applyRate($shipment, $rate); | |
} | |
$shipment->save(); | |
} | |
$order->set('shipments', $shipments); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BTW, if I understood well this code is creating an empty customer profile in order to create shipments . Problem is that later, on order overview page, where user is setting shipping address that empty profile (address) is also offered. Drop-down for selecting shipping address looks like:
and that "Customer information #498" option is selected by default and all address fields are empty for it (similar as for entering new address". Can this be removed somehow?