You are here

function commerce_cps_add_order_shipping in Commerce Cart Pane 7

Add shipping service to order. If no shipping service is passed the current shipping service will be recalculated for order

Parameters

[type] $order :

[type] $service_name :

9 calls to commerce_cps_add_order_shipping()
commerce_cps_commerce_cart_product_add in modules/shipping/commerce_cps.module
Implements hook_commerce_cart_product_add().
commerce_cps_commerce_cpc_coupon_attached in modules/shipping/commerce_cps.module
Implements hook_commerce_cpc_coupon_attached().
commerce_cps_commerce_cpc_coupon_detached in modules/shipping/commerce_cps.module
Implements hook_commerce_cpc_coupon_detached().
commerce_cps_entity_delete in modules/shipping/commerce_cps.module
Implements hook_entity_delete().
commerce_cps_entity_update in modules/shipping/commerce_cps.module
Implements hook_entity_update().

... See full list

File

modules/shipping/commerce_cps.module, line 174

Code

function commerce_cps_add_order_shipping($order, $service_name = NULL) {

  // if no shipping service is passed check if order has some
  // shipping service chosen
  if (empty($service_name)) {
    $service_name = commerce_cps_get_order_shipping($order);
    if (empty($service_name)) {
      return;
    }
  }

  // reload an order to void system error https://www.drupal.org/node/2275495
  // It usually happens if user switches shipping on the cart after 14+ sec
  // after page was reloaded. Unclear issue - like some data in order has
  // been expired after 14+ sec..
  $order = commerce_order_load($order->order_id);

  // force shipping recalculation
  if (isset($order->shipping_rates)) {
    unset($order->shipping_rates);
  }

  // Make the chosen service available to the order.
  commerce_shipping_service_rate_order($service_name, $order);
  if (!isset($service_name)) {
    if (empty($order->shipping_rates)) {

      // No available rate.
      return;
    }
    $service_name = key($order->shipping_rates);
  }

  // Delete any existing shipping line items from the order.
  commerce_shipping_delete_shipping_line_items($order, TRUE);

  // Extract the unit price from the calculated rate.
  $rate_line_item = $order->shipping_rates[$service_name];
  $rate_line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $rate_line_item);
  $unit_price = $rate_line_item_wrapper->commerce_unit_price
    ->value();

  // Create a new shipping line item with the calculated rate from the form.
  $line_item = commerce_shipping_line_item_new($service_name, $unit_price, $order->order_id, $rate_line_item->data, $rate_line_item->type);

  // Save and add the line item to the order.
  $new_line_item = commerce_shipping_add_shipping_line_item($line_item, $order, TRUE);
  commerce_order_save($order);
  return $order;
}