Saturday, May 7, 2011

Programmatically create order in Magento

Hello,

This is the toughest work I ever did in Magento. Since last few days I am working on Magento and Channel Advisor(CA) Integration.  The requirement was to fetch order from CA and process them in Magento. We were using Channel Advisor PHP API to fetch orders from CA.

CA order service API needs order criteria to fetch orders. Following is the order criteria we were passing.


$OrderCriteria = array(
'OrderCreationFilterBeginTimeGMT'=> $date1,
'OrderCreationFilterEndTimeGMT'=> $date2,
'StatusUpdateFilterBeginTimeGMT' => $date1,
'StatusUpdateFilterEndTimeGMT' => $date2,
'JoinDateFiltersWithOr' => true,
'DetailLevel' => 'Complete',
'ExportState' => 'NotExported',
'OrderStateFilter' => 'Active',
'PaymentStatusFilter' => 'Cleared',
'CheckoutStatusFilter'  => 'Completed',
'ShippingStatusFilter'  =>'Unshipped',
'PageNumberFilter'=>1,
'PageSize'=>20
);



$arrData = array(
        'accountID'=>$accountID,
        'orderCriteria'=>$OrderCriteria
);
$result=$client->GetOrderList($arrData);               
$results=$result->GetOrderListResult->ResultData;
$orders=$results->OrderResponseItem ;

It will return first 20 orders that match above criteria.

Now here is the tough job. We have to fetch all the order data and have to create order in Magento. Following is the code for it.


foreach($orders as $order)
{

$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()
->getStore('default')->getId());
$customer = Mage::getModel('customer/customer')
->setWebsiteId(1)
->loadByEmail($order->BuyerEmailAddress);                  
                   
if(empty($customer)){
$quote->assignCustomer($customer);
}
else{
$quote->setCustomerEmail($order->BuyerEmailAddress);
}

$orderitems = $order->ShoppingCart->LineItemSKUList->OrderLineItemItem;


foreach($orderitems as $orderItem){
        $product = $newProd
                               ->load($newProd->getIdBySku($orderItem->SKU));

        $buyInfo = array(
         'qty' => $orderItem->Quantity
         );

         $quote->addProduct($product, new Varien_Object($buyInfo));                    

}


$region=$order->ShippingInfo->Region;
$regionid = GetRegionId($region);


$firstName = ($order->BillingInfo->FirstName != "")
? ($order->BillingInfo->FirstName)
:($order->ShippingInfo->FirstName);
if(empty($firstName)){
$firstName = "FirstName";  
}

$firstName = ($order->BillingInfo->FirstName != "") 
? ($order->BillingInfo->FirstName) 
:($order->ShippingInfo->FirstName);
if(empty($firstName)){
$firstName = "FirstName";    
}

$lastName = ($order->BillingInfo->LastName != "") 
? ($order->BillingInfo->LastName) 
: ($order->ShippingInfo->LastName);
if(empty($lastName)){
$lastName = "LastName";    
}
                    
$street = (($order->BillingInfo->AddressLine1 != "")
? ($order->BillingInfo->AddressLine1) 
: ($order->ShippingInfo->AddressLine1)).
(($order->BillingInfo->AddressLine2 != "") 
? ($order->BillingInfo->AddressLine2) 
: ($order->ShippingInfo->AddressLine2));

if(empty($street)){
$street = "Street";    
}
                    
$city = ($order->BillingInfo->City != "") 
? ($order->BillingInfo->City) 
: ($order->ShippingInfo->City);
if(empty($city)){
$city = "City";    
}
                    
$postCode = ($order->BillingInfo->PostalCode != "") 
? ($order->BillingInfo->PostalCode) 
: ($order->ShippingInfo->PostalCode);
if(empty($postCode)){
$postCode = "00000";    
}
                    
$telephone = ($order->BillingInfo->PhoneNumberDay != "") 
? ($order->BillingInfo->PhoneNumberDay) 
: ($order->ShippingInfo->PhoneNumberDay);

if(empty($telephone)){
$telephone = "00000";    
}
                    
$addressData = array(
'firstname' => $firstName,
'lastname' => $lastName,
'street' => $street,
'city' => $city,
'postcode' => $postCode,
'telephone' => $telephone,
'country_id' => $order->ShippingInfo->CountryCode,
'region_id' => $regionid
);

$billingAddress = $quote
                             ->getBillingAddress()
                             ->addData($addressData);

$firstName = ($order->ShippingInfo->FirstName != "") 
? ($order->ShippingInfo->FirstName) 
: ($order->BillingInfo->FirstName);
if(empty($firstName)){
$firstName = "FirstName";    
}
                    
$lastName = ($order->ShippingInfo->LastName != "") 
? ($order->ShippingInfo->LastName) 
: ($order->BillingInfo->LastName);
if(empty($lastName)){
$lastName = "LastName";    
}
                    
$street = (($order->ShippingInfo->AddressLine1 != "") 
? ($order->ShippingInfo->AddressLine1) 
: ($order->BillingInfo->AddressLine1)).
(($order->ShippingInfo->AddressLine2 != "") 
? ($order->ShippingInfo->AddressLine2) 
: ($order->BillingInfo->AddressLine2));                    
if(empty($street)){
$street = "Street";    
}
                    
$city = ($order->ShippingInfo->City != "") 
? ($order->ShippingInfo->City) 
: ($order->BillingInfo->City);
if(empty($city)){
$city = "City";    
}
                    
$postCode = ($order->ShippingInfo->PostalCode != "") 
? ($order->ShippingInfo->PostalCode) 
: ($order->BillingInfo->PostalCode);
if(empty($postCode)){
$postCode = "00000";    
}
                    
$telephone = ($order->ShippingInfo->PhoneNumberDay != "") 
? ($order->ShippingInfo->PhoneNumberDay) 
: ($order->BillingInfo->PhoneNumberDay);
if(empty($telephone)){
$telephone = "00000";    
}
                    
$addressData = array(
'firstname' => $firstName,
'lastname' => $lastName,
'street' => $street,
'city' => $city,
'postcode' => $postCode,
'telephone' => $telephone,
'country_id' => $order->ShippingInfo->CountryCode,
'region_id' => $regionid
);

$shippingAddress = $quote->getShippingAddress()->addData($addressData);
                    
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
                        ->setShippingMethod('perproductshipping_ground')
                        ->setPaymentMethod('purchaseorder');
                        
$quote->getPayment()->importData(array(
'method' => 'purchaseorder',
'po_number' => $order->ClientOrderIdentifier));
         
$quote->collectTotals()->save();
                    
Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0"); 
                    
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();




}

That's it and it will create new purchase order in magento. Limitations of above code are as follow.

1) It will only create purchase order
2) It will only be useful for simple products.

I hope this post helps you.

Thanks,



6 comments:

  1. Nice code. One thing I'm struggling with - any idea how to set the created_at date?

    ReplyDelete
  2. Hi James,

    There is not any function to set created_at date. But you can do it by directly changing database entry.

    ReplyDelete
  3. hi! else you can override Mage_Sales_Model_Mysql4_Abstract and change the method _prepareDataForSave, changing from
    if (!$object->getId() || $object->isObjectNew()) {
    to
    if ((!$object->getId() || $object->isObjectNew()) && !$object->getCreatedAt())

    ReplyDelete
  4. you saved me man thank you very much

    ReplyDelete