Multiple Shipping Addresses

On the multiple shipping addresses page, Magento presents a list of addresses to use for each order. These are passed to the MultishippingController‘s addressPostAction method using the post parameter name “ship”. Here’s an example of the array that gets posted:

<?php
array (size=3)
  0 => 
    array (size=1)
      2540 => 
        array (size=2)
          'qty' => string '1' (length=1)
          'address' => string '93' (length=2)
  1 => 
    array (size=1)
      2542 => 
        array (size=2)
          'qty' => string '1' (length=1)
          'address' => string '93' (length=2)
  2 => 
    array (size=1)
      2544 => 
        array (size=2)
          'qty' => string '1' (length=1)
          'address' => string '94' (length=2)
  • The key of each of the array is the order item id.
  • qty is the quantity that is required
  • address contains an id of a customer/address entity (from the EAV table customer_address_entity)

The Multishipping Controller passes the array to the method setShippingItemsInformation of a singleton of checkout/type_multishipping model. It’s here that the model firstly validates that the customer hasn’t ordered too many of the items (set in config shipping/option/checkout_multiple_maximum_qty – and set in the same place in the admin area).

  • All shipping addresses which may have previously set on the quote are now removed, and the new ones are assigned using the method ** $this->_addShippingMethod($quoteItemId, $data)** where $data is the individual elements of the array above:
<?php
protected function _addShippingItem($quoteItemId, $data)
    {
        $qty       = isset($data['qty']) ? (int) $data['qty'] : 1;
        //$qty       = $qty > 0 ? $qty : 1;
        $addressId = isset($data['address']) ? $data['address'] : false;
        $quoteItem = $this->getQuote()->getItemById($quoteItemId);

        if ($addressId && $quoteItem) {
            /**
             * Skip item processing if qty 0
             */
            if ($qty === 0) {
                return $this;
            }
            $quoteItem->setMultishippingQty((int)$quoteItem->getMultishippingQty()+$qty);
            $quoteItem->setQty($quoteItem->getMultishippingQty());
            $address = $this->getCustomer()->getAddressById($addressId);
            if ($address->getId()) {
                if (!$quoteAddress = $this->getQuote()->getShippingAddressByCustomerAddressId($address->getId())) {
                    $quoteAddress = Mage::getModel('sales/quote_address')->importCustomerAddress($address);
                    $this->getQuote()->addShippingAddress($quoteAddress);
                }

                $quoteAddress = $this->getQuote()->getShippingAddressByCustomerAddressId($address->getId());
                if ($quoteAddressItem = $quoteAddress->getItemByQuoteItemId($quoteItemId)) {
                    $quoteAddressItem->setQty((int)($quoteAddressItem->getQty()+$qty));
                } else {
                    $quoteAddress->addItem($quoteItem, $qty);
                }
                /**
                 * Require shiping rate recollect
                 */
                $quoteAddress->setCollectShippingRates((boolean) $this->getCollectRatesFlag());
            }
        }
        return $this;
    }
  •  $quote->getShippingAddressByCustomerAddressId($addressId)

    attempts to find whether this particular customer’s address has been used for any items in this specific quote before (this uses the sales_flat_quote_address table, using the Quote’s id, the type of shipping (Mage_Sales_Model_Quote_Address::TYPE_SHIPPING) and the customer’s address id (customer_address_entity table).

  • If a quote address is not found, then one is created, and the customer’s address is imported into it using the sales/quote_address method importCustomerAddress
  • The shipping address is added to the quote object.
  • The quote address is then queried using getItemByQuoteItemId($quoteItemId) to see if this address already contains an item with the same quote id. If it does, the quantities are added together, otherwise the item is added to the quote address model.

Back in the checkout/type_multishipping model’s setShippingItemsInformation method

<?php
      if ($billingAddress = $quote->getBillingAddress()) {
                $quote->removeAddress($billingAddress->getId());
            }

            if ($customerDefaultBilling = $this->getCustomerDefaultBillingAddress()) {
                $quote->getBillingAddress()->importCustomerAddress($customerDefaultBilling);
            }

            foreach ($quote->getAllItems() as $_item) {
                if (!$_item->getProduct()->getIsVirtual()) {
                    continue;
                }

                if (isset($itemsInfo[$_item->getId()]['qty'])) {
                    if ($qty = (int)$itemsInfo[$_item->getId()]['qty']) {
                        $_item->setQty($qty);
                        $quote->getBillingAddress()->addItem($_item);
                    } else {
                        $_item->setQty(0);
                        $quote->removeItem($_item->getId());
                    }
                 }

            }

  • The default billing address is obtained, and all items with a set quantity in the data array get added to the address. If there’s no quantity then the item is removed from the quote. The customer can change the billing address for the quote in a later stage of the multishipping process.

Converting the order to a sales order

This takes place at the last stage of the multishipping process, in the overviewPostAction. After a host of validation,

 $this->_getCheckout()->createOrders(); 

is called. The checkout object is an instance of the Mage_Checkout_Model_Type_Multishipping

<?php
        try {
            foreach ($shippingAddresses as $address) {
                $order = $this->_prepareOrder($address);

                $orders[] = $order;
                Mage::dispatchEvent(
                    'checkout_type_multishipping_create_orders_single',
                    array('order'=>$order, 'address'=>$address)
                );
            }

– Each of the addresses are looped over and an order is created for each one. Into the _prepareOrder method, amongst validation, the parts of the quote are converted to their order counterparts.
– The Mage_Sales_Quote_Convert class is responsible for this:

 $order = $convertQuote->addressToOrder($address);

– Takes values from the address object and puts them onto the order object. These values are found in the

** global/fieldsets/sales_convert_quote_address **, any children with the to_order child will be copied over.

 $convertQuote->addressToOrderAddress($quote->getBillingAddress()) 

– Takes values from global/fieldsets/ sales_convert_quote_address and uses the child to_order_address to copy values from the billing address to the order address.

<?php
if ($address->getAddressType() == 'billing') {
            $order->setIsVirtual(1);
        } else {
            $order->setShippingAddress($convertQuote->addressToOrderAddress($address));
        }
 

If the address type is set to billing, then set the order to virtual, otherwise convert address to an order address using the same method as above. The payment is then converted to an order payment::

 $convertQuote->paymentToOrderPayment($quote->getPayment()) 

– This uses the global/fieldsets node sales_convert_quote_payment and to_order_payment

<?php
if (Mage::app()->getStore()->roundPrice($address->getGrandTotal()) == 0) {
            $order->getPayment()->setMethod('free');
        }
[/php]
 - If the price of the items in the address object is zero, the payment method is set as free.


<?php
 foreach ($address->getAllItems() as $item) {
            $_quoteItem = $item->getQuoteItem();
            if (!$_quoteItem) {
                throw new Mage_Checkout_Exception(Mage::helper('checkout')->__('Item not found or already ordered'));
            }
            $item->setProductType($_quoteItem->getProductType())
                ->setProductOptions(
                    $_quoteItem->getProduct()->getTypeInstance(true)->getOrderOptions($_quoteItem->getProduct())
                );
            $orderItem = $convertQuote->itemToOrderItem($item);
            if ($item->getParentItem()) {
                $orderItem->setParentItem($order->getItemByQuoteItemId($item->getParentItem()->getId()));
            }
            $order->addItem($orderItem);
        }
 

- Each order item in the address is looped over and an order item is created from each quote item. This sets a few items itself, such as the quote item id, product type, quantity backordered, base original price, quote parent id, and store id. It also sets all of the product options on the quote item, then copies all entries in the global/fieldset/sales_convert_quote_item children with the child to_order_item

If there's a discount on the order item, this is copied over to the order item discount here:

<?php
if (!$item->getNoDiscount()) {
            Mage::helper('core')->copyFieldset('sales_convert_quote_item', 'to_order_item_discount', $item, $orderItem);
        }
  • Events are fired for each of the conversion routines in the sales/convert_quote model.

Back in the checkout/type_multishipping model

  • After each order has been created, a checkout_type_multishipping_create_orders_single event is dispatched.
  • For each of the orders, an email is scheduled to be sent as confirmation to the customer.
  • Session variables are set for use elsewhere:
Mage::getSingleton('core/session')->setOrderIds($orderIds);
Mage::getSingleton('checkout/session')->setLastQuoteId($this->getQuote()->getId());
  • Another event is dispatched: checkout_submit_all_after

Back in the multishipping controller

<?php
$this->_getState()->setActiveStep(
                Mage_Checkout_Model_Type_Multishipping_State::STEP_SUCCESS
            );
            $this->_getState()->setCompleteStep(
                Mage_Checkout_Model_Type_Multishipping_State::STEP_OVERVIEW
            );
            $this->_getCheckout()->getCheckoutSession()->clear();
            $this->_getCheckout()->getCheckoutSession()->setDisplaySuccess(true);
            $this->_redirect('*/*/success');

- The active step is set to success, the checkout session is cleared, a message to the user is primed and they're redirected to the success page.

Summary Notes

  • Each quote item can have its own address. The sales_flat_quote_address and sales_flat_quote_item are linked using the sales_flat_quote_address_item table.
  • When the quote is converted to an order, each shipping address creates a new order. It's the addresses (shipping and billing) which have a list of order items. The order id is set confusingly on the order addresses as parent_id, this is done in the order's addAddress method:
<?php
public function addAddress(Mage_Sales_Model_Order_Address $address)
    {
        $address->setOrder($this)->setParentId($this->getId());
        if (!$address->getId()) {
            $this->getAddressesCollection()->addItem($address);
        }
        return $this;
    }